带有 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.
您必须将 priority 设置为 -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
从一个小调查(fiddle)看来 $element
传递给 link
函数的是 ng-repeat
插入的 HTML 注释 helper.
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屋!