Mastering Web Application

(Rick Simeone) #1

Building Advanced Directives


The ng-repeat directive has transclude: 'element' and priority: 1000, so
generally all attributes that appear on the ng-repeat element are transcluded to
appear on the cloned repeated elements.


We gave out if directive a priority of 500 , which is less than ng-
repeat. This means that if you put it on the same element as an
ng-repeat, the expression that if watches will refer to the scope
created by each iteration of ng-repeat.

In this directive, transclusion allowed us to get hold of the contents of the directive's
element, bound to the correct scope, and conditionally insert it into the DOM.


Next we are going to change tack and look at providing controllers specifically
for directives.


Understanding directive controllers


A controller in AngularJS is an object attached to a DOM element that initializes and
adds behaviour to the scope at that element.


We have already seen many application controllers, instantiated
by the ng-controller directive. These controllers should not
interact directly with the DOM but should deal only with the
current scope.

A directive controller is a special form of controller that is defined by a directive
and instantiated each time that directive appears on a DOM element. Its role is to
initialize and provide behavior for the directive rather than a scope.


You define a directive controller using the controller property on the directive
definition object. The controller property can be a string containing the name of
a controller already defined on a module:


myModule.directive('myDirective', function() {
return {
controller: 'MyDirectiveController'
};
});
myModule.controller('MyDirectiveController', function($scope) {
...
});
Free download pdf