var cvl = angular.module('cvl',[]); cvl.directive('controllerExample',[function(){ return { restrict: 'A',//attribute binding template: '<div ng-click"setRed" ng-class="controllerClass">Controller Click</div>', controller: ['$scope', '$element', function ($scope, $element) { $scope.setRed = function(){ //binds to ng-class in the template $scope.controllerClass = 'red'; } }]}}]); cvl.directive('linkerExample',[ function(){ return { restrict: 'A', template: '<div>Linker Click</div>', link: function(scope, element, attrs) { var btn = element; element.on('click', toggle); function toggle() { element.addClass('red'); } }}}]);
<h3>App</h3> <div ng-app="cvl"> <div controller-example=""></div> <div linker-example=""></div> </div> <br/> <br/> <br/> <hr/> <h3>Explination</h3> <p><i>This script still requires some debugging. Have not wroked out how to efficiently debug in jsfiddle.</i></p> <p>Both examples do the same thing.</p> <p>Controllers in directives work the same way as controllers declared in the html. The dependencies are a bit different.</p> <p>Linkers require more DOM manipulation.</p> <p> Another way to think of the relationship between linkers and controllers, though not usually shown in the beginner examples, is to use linkers to dynamically modify a base template, then pass the work over to controllers. </p> <p> In my work with binding directives directly to xml documents, doing all the work in linkers has a performance increase when there is many instances of the directive invoked on the page. But no real difference when one instance of a directive is on a page. In the example of an xml document with 100 users on the page, the controller method seemed to have poorer performance. I did not formally benchmark and this may change between versions of AngularJs.</p>
red{ color:red; }