带有ng-repeat的元素上的Angular js自定义指令-无法设置CSS类 [英] Angular js Custom Directive on element with ng-repeat - Can't set CSS classes
问题描述
我正在尝试对具有ng-repeat的元素使用自定义指令,如下所示:
I'm trying to use a custom directive on an element with ng-repeat, like so:
<article ng-repeat="product in ctrl.products" class="product entity"
product="product" selected-retailer="ctrl.selectedRetailer"></article>
我已经读到,为了使其正常工作,您需要将自定义指令的优先级设置为高于ng-repeat指令的优先级.因此,我已经像这样定义了指令,将优先级设置为1001:
I've read that, in order for this to work, you need to set the priority on your custom directive to something higher than the ng-repeat directive. So I've defined my directive like so, setting the priority to 1001:
angular.module('MainApp')
.directive('product', function () {
return {
restrict: 'A',
scope: {
product: '=',
selectedRetailer: '='
},
priority: 1001,
templateUrl: '/Static/Templates/product.html',
link: function ($scope, $element, $attributes) {
$element.addClass('testCssClass');
}
};
});
...这可行,它遍历我的产品.
...and this works, it loops through my products.
问题是,我还试图使用以下指令在指令的元素(文章)上设置CSS类:
The problem is, I'm also trying to set a CSS class on the directive's element (article) using:
$element.addClass('testCssClass');
...在链接功能中,但似乎不起作用.
...in the link function, but it doesn't seem to work.
但是,如果我删除ng-repeat并仅显示第一个产品项,就像这样:
But if I remove ng-repeat and just show first product item, like so:
<article class="product entity" product="ctrl.products[0]"
selected-retailer="ctrl.selectedRetailer"></article>
... CSS类显示得很好(即产品实体testCssClass").
...the CSS class shows up just fine (i.e. "product entity testCssClass").
如何使它与ng-repeat一起使用?
How can I get this to work with ng-repeat?
推荐答案
这确实是Angular非常令人不愉快的惊喜形式.
This was indeed a very unpleasant surprise form Angular.
您必须将优先级设置为-1001 ,它才能正常工作.原因:(来自$compile
服务中优先级的文档)
You have to set priority to -1001 for it to work. Reason: (from the docs of priority in the $compile
service)
优先级
[...]优先编译具有更高数字优先级的指令. [...]链接后功能以相反的顺序运行
Priority
[...] Directives with greater numerical priority are compiled first. [...] post-link functions are run in reverse order
从一个小的调查(小提琴)看来,$element
传递给了link
函数是ng-repeat
插入的 HTML注释帮助程序.
From a small investigation (fiddle) it seems that the $element
passed to the link
function is the HTML comment helper inserted by ng-repeat
.
这篇关于带有ng-repeat的元素上的Angular js自定义指令-无法设置CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!