Mastering Web Application

(Rick Simeone) #1

Building Your Own Directives


This binding is equivalent to $parse the expression in the attribute and exposing the
parsed expression function on the isolated scope:


parentGet = $parse(attrs['attribute3']);
scope.isolated3 = function(locals) {
return parentGet(parentScope, locals);
};

Implementing the widget


The following is the pagination directive definition object:


myModule.directive('pagination', function() {
return {
restrict: 'E',
scope: {
numPages: '=',
currentPage: '='
},
template: ...,
replace: true,

The directive is restricted to appear as an element. It creates an isolated scope
with numPages and currentPage data, which is bound to attributes num-pages
and current-page, respectively. The directive element will be replaced with the
template shown earlier:


link: function(scope) {
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.isActive = function(page) {
return scope.currentPage === page;
};

scope.selectPage = function(page) {
if (! scope.isActive(page) ) {
scope.currentPage = page;
}
Free download pdf