controller

The controller is pretty similar to the link function and has almost the same parameters, except itself. However, the purpose of the controller is totally different.

While it is recommended that you use the link to bind events and create behaviors,the controller should be used to create behaviors that will be shared with other directives by means of the require property:

directives.html
snippet
parking.directive("accordion", function() {
return {
template: "<div ng-transclude></div>",
restrict: "E",
transclude: true,
controller: function($scope, $element, $attrs, $transclude) {
var accordionItens = [];
var addAccordionItem = function(accordionScope) {
accordionItens.push(accordionScope);
};
var closeAll = function() {
angular.forEach(accordionItens, function(accordionScope) {
accordionScope.active = false;
});
};
return {
addAccordionItem: addAccordionItem,
closeAll: closeAll
};
}
};
});
snippet
parking.directive("accordionItem", function() {
return {
templateUrl: "accordionItem.html",
restrict: "E",
scope: {
title: "@"
},
transclude: true,
require: "^accordion",
link: function(scope, element, attrs, ctrl, transcludeFn) {
ctrl.addAccordionItem(scope);
element.bind("click", function() {
ctrl.closeAll();
scope.$apply(function() {
scope.active = !scope.active;
});
});
}
};
});
Related Tutorial
7. replace
9. scope
11. link
12. require
14. compile
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 # # # # #