Mastering Web Application

(Rick Simeone) #1

Building Advanced Directives


Creating a controller-based pagination directive


There is a lot of overlap in functionality between directive controllers and link
functions. It is often possible to use a controller instead of a link function. Here is the
pagination directive from Chapter 9, Building Advanced Directives, but this time using
a directive controller instead of a link function:


myModule.directive('pagination', function() {
return {
restrict: 'E',
scope: { numPages: '=', currentPage: '=', onSelectPage: '&' },
templateUrl: 'template/pagination.html',
replace: true,
controller: ['$scope, '$element', '$attrs',
function($scope, $element, $attrs) {
$scope.$watch('numPages', function(value) {
$scope.pages = [];
for(var i=1;i<=value;i++) {
$scope.pages.push(i);
}
if ( $scope.currentPage > value ) {
$scope.selectPage(value);
}
});
$scope.noPrevious = function() {
return $scope.currentPage === 1;
};
...
}]
...
});

In this simple case, the only difference between this version and the one that used a
link function is that, while the link function is passed scope, element, attrs, and
controller parameters, the directive controller must use the dependency injection
annotations to be provided with the $scope, $element, and $attrs services.


Understanding the difference between


directive controllers and link functions


When choosing between using link functions or directive controllers it is helpful to
be aware of a few differences.

Free download pdf