I was reading through this article:
http://teropa.info/blog/2014/10/24/how-ive-improved-my-angular-apps-by-banning-ng-controller.html
Which proposes that controllers be integrated into directives like this in order to remove the need to ever use 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 proposed 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 achieves the exact same thing as the version with the controller without ever needing to make a controller. So I'm curious as to what the pros and cons of either method are versus writing angular traditionally with ng-controller, and whether controllers are even necessary by the end of it.
Here is the plunker for the first, and here is the second.
The link function is like a directive's constructor. It is executed only once during the initialization process of the directive. There's no way to get the link function to run again for the same instance of an already initialized directive.
Answer:The link option is just a shortcut to setting up a post-link function. controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.
The ng-controller Directive in AngularJS is used to add a controller to the application.
A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.
In directives, you should use link function whenever you can. Use controllers only when communication to other directives is needed.
You can find more about this discussion here. Specifically this best practice statement:
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With