Reputation: 16445
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.
Upvotes: 6
Views: 1192
Reputation: 1013
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.
Upvotes: 4
Reputation: 4611
Directives and Controllers are two totally different things.
Direvtives should be used for DOM manipulations.
if you want to know use controller inside DDO or use link function for your logic, then answer will be you should use controller in DDO in that cases when you want provide API and require your directive in other directives and use that API in extended directive
Controllers can't be replaced by directive
Controller should contain your businesses logic and it cant be replaced by directive and shouldn't have DOM manipulations.
Upvotes: -1