Can the controllers be completely replaced by the link function in the directive?

I read this article:

http://teropa.info/blog/2014/10/24/how-ive-improved-my-angular-apps-by-banning-ng-controller.html

What suggests integrating controllers into such directives in order to remove the need to use an ng controller:

angular.module('contestantEditor', []) .directive('cContestantEditorForm', function() { return { scope: { contestants: '=' }, templateUrl: 'contestant_editor.html', replace: true, controller: 'ContestantEditorFormCtrl', controllerAs: 'ctrl', bindToController: true }; }) .controller('ContestantEditorFormCtrl', function($scope) { this.contestant = {}; this.save = function() { this.contestants.push(this.contestant); this.contestant = {}; }; }); 

In the comments, however, someone else suggested this solution:

 angular.module('contestantEditor', []) .directive('cContestantEditorForm', function () { return { scope: { contestants: '=' }, templateUrl: 'contestant_editor.html', replace: true, link: function (scope) { scope.contestant = {}; scope.save = function() { scope.contestants.push(scope.contestant); scope.contestant = {}; }; } }; }); 

It does the same thing as the controller version, without even requiring the creation of a controller. So I'm curious what the pros and cons of any method are compared to writing angular traditionally with an ng controller, and whether controllers are needed by the end.

Here is the plunker for the first, and here is the second.

+6
source share
2 answers

In directives, you should use the link function whenever you can. Use controllers only when communication with other directives is necessary.

Read more about this discussion here . In particular, this is a statement of best practice:

Best practice : use a controller if you want to provide the API with other directives. Otherwise use the link .

+4
source

Directives and controllers are two completely different things.

Direvtives should be used to manipulate the DOM.

if you want to know how to use the controller inside DDO or use the link function for your logic, then the answer will be that you should use the controller in DDO in cases where you want to provide an API and require a directive in other directives and use this API in extended directive


Controllers cannot be replaced by directive

The controller must contain the logic of your business, and it cannot be replaced by a directive and must not have DOM manipulations.

-1
source

Source: https://habr.com/ru/post/981010/


All Articles