[英]Wrapping an ngRepeat inside another directive
我正在尝试为我的应用程序编写一个分页器作为指令,但是我似乎无法使其正常工作。 我看过的所有地方都建议使用$compile
,但我根本无法使用它。
这就是我所拥有的,您可以在此处观看现场演示
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);
}
}
};
});
如您所知,我对angular还是很陌生,任何帮助将不胜感激。
我设法通过将数据存储在main指令的控制器上而不是作用域上来使它起作用,您可以在此处看到。
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);
}
}
};
});
首先,您的指令不具有相同的范围:
其次,在您的内部指令中,您引用外部作用域变量items
:
.attr('ng-repeat', 'item in items | limitTo:amount');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.