Reputation: 2114
I'm trying to write a paginator as a directive for my application, but I can't seem to get it to work. Every where I've looked suggests using $compile
, but I can't get that to work at all.
This is what I have, and you can view a live demo here
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
});
app.directive('myPaginator', function() {
return {
restrict : 'A',
priority : 1000,
scope : {
items : '=myPaginator'
},
controller : function($scope) {
$scope.amount = 5;
}
};
});
app.directive('myPaginatorItem', function($compile) {
return {
restrict : 'A',
require : '^myPaginator',
priority : 999,
compile : function(element) {
element
.removeAttr('my-paginator-item')
.attr('ng-repeat', 'item in items | limitTo:amount');
return function($scope, element) {
$compile(element)($scope);
}
}
};
});
As you can probably tell, I'm quite new to angular, and any help will be greatly appreciated.
Upvotes: 2
Views: 210
Reputation: 2114
I've managed to make it work by storing the data on the main directive's controller, rather than on the scope, which you can see here.
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
});
app.directive('myPaginator', function() {
return {
restrict : 'A',
priority : 1000,
replace : true,
scope : {
items : '=myPaginator'
},
controller : function($scope) {
this.items = $scope.items;
this.amount = 5;
}
};
});
app.directive('myPaginatorItem', function($compile) {
return {
restrict : 'A',
require : '^myPaginator',
priority : 999,
scope : {},
compile : function(element) {
element
.removeAttr('my-paginator-item')
.attr('ng-repeat', 'item in paginator.items | limitTo:paginator.amount');
return function($scope, element, $attrs, paginator) {
$scope.paginator = paginator;
$compile(element)($scope);
}
}
};
});
Upvotes: 1
Reputation: 32367
First, Your directives doesn't share the same scope:
Second, Inside you directive you refer to an outer scope variable items
:
.attr('ng-repeat', 'item in items | limitTo:amount');
Upvotes: 0