AngularJS - ng-click 指令的链接功能 [英] AngularJS - ng-click in directive's link function
问题描述
我正在处理一个指令,并且在 link
函数中,在迭代数组模型时,想要使用 ng-click
处理程序将元素附加到页面附在他们身上.像这样:
I'm working on a directive, and in the link
function, while iterating over a array model, want to append elements to the page with ng-click
handlers attached to them. Something like this:
app.directive('foo', function(){
restrict: 'A',
link: function(scope, elem){
... // some logic
for (var i = 1; i < numberOfPages + 1; i++) {
elem.append('<li ng-click="bar('+i+')">'+i+'</li>');
}
}
});
但是 ng-click
处理程序在到达时就死了.如何让处理程序按预期运行?
But the ng-click
handlers are dead on arrival. How can I make the handlers behave as expected?
推荐答案
在 AngularJS 中,你不能真正将指令附加到你的自定义指令中,而不必做一些奇怪的 $compile
逻辑来获得ngClick
指令进行注册.大概是这样的:
In AngularJS, you can't really append directives to your custom directive without having to do some weird $compile
logic to get the ngClick
directives to register. Probably something like:
// include $compile
// ... append li elements
scope.$apply(function() {
$compile(elem)(scope);
});
顺便说一下,我不知道这是否有效,因此如果无效,请不要追究我的责任.通常,您解决此问题的方法是使用如下所示的指令:
I have no idea if that works by the way, so don't hold me accountable if it doesn't. Generally, the way you solve this problem is with a directive that looks like this:
angular.directive('pager', function() {
return {
restrict: 'AEC',
scope: {
numPages: '=pager',
pageFn: '='
},
template: '<ul><li ng-repeat="page in pages" ng-click="executePage(page)">{{page}}</li></ul>',
link: function(scope, elem, attrs) {
scope.pages = [];
scope.$watch('numPages', function(pages) {
if(!pages) return;
scope.pages = [];
for(var i = 1; i <= pages: i++) {
scope.pages.push(i);
}
});
scope.executePage = function(page) {
if(scope.pageFn){
// Additional Logic
scope.pageFn(page);
}
};
}
};
})
然后在您的 html 中,您将编写如下指令:
Then in your html you would write the directive like this:
<my-directive>
<div pager="numberOfPages" page-fn="goToPage"></div>
</my-directive>
goToPage
是一个在 myDirective
指令中定义的函数,它接受一个页面参数.在这一点上,分页指令也足够抽象,可以在多个地方使用,而不必担心外部功能.
goToPage
is a function that is defined in the myDirective
directive and accepts a page parameter. At this point, the paging directive is also abstract enough for you to use in multiple places and not really have to worry about external functionality.
这篇关于AngularJS - ng-click 指令的链接功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!