动态添加在NG-重复指令 [英] dynamically adding directives in ng-repeat
问题描述
我想在NG-重复动态添加不同的指令,但是输出是不是被PTED作为指令间$ P $。
I am trying to dynamically add different directives in an ng-repeat however the output is not being interpreted as directives.
我已经在这里添加了一个简单的例子: http://plnkr.co/edit/6$p$ppoqvmcnJJWzhZZKq
I've added a simple example here: http://plnkr.co/edit/6pREpoqvmcnJJWzhZZKq
控制器:
$scope.colors = [{name:"red"}, {name: "blue"}, {name:"yellow"}];
指令:
app.directive("red", function () {
return {
restrict: 'C',
template: "RED directive"
}
});
HTML:
<ul>
<li ng-repeat="color in colors">
<span class="{{color.name}}"></span>
</li>
</ul>
如何使角度拿起在类
指定的指令,通过输出NG-重复?
How do I make angular pick up the directive specified in the class
that is output via ng-repeat?
推荐答案
我知道这是一个老问题,但谷歌把我带到这里,我不喜欢这里的答案......他们似乎很复杂的东西,应该很简单。所以我创造了这个指令:
I know this is an old question, but google brought me here, and I didn't like the answers here... They seemed really complicated for something that should be simple. So I created this directive:
/**
* Author: Eric Ferreira <http://stackoverflow.com/users/2954747/eric-ferreira> ©2015
*
* This directive will simply take a string directive name and do a simple compilation.
* For anything more complex, more work is needed.
*/
angular.module('attributes', [])
.directive('directive', function($compile, $interpolate) {
return {
template: '',
link: function($scope, element, attributes) {
element.append($compile('<div ' + attributes.directive + '></div>')($scope));
}
};
})
;
对于这一问题的具体情况下,可以只改写指令位,使其按类指令适用于跨度,像这样:
For the specific case in this question, one can just rewrite the directive a bit to make it apply the directive to a span by class, as so:
angular.module('attributes', [])
.directive('directive', function($compile, $interpolate) {
return {
template: '',
link: function($scope, element, attributes) {
element.replaceWith($compile('<span class=\"' + attributes.directive + '\"></span>')($scope));
}
};
})
;
然后就可以用这个任意位置,动态选择按名称指令。使用它像这样:
Then you can use this anywhere and select a directive by name dynamically. Use it like so:
<li ng-repeat="color in colors">
<span directive="{{color.name}}"></span>
</li>
我特意保留了这个指令,简单明了。你可能(也可能会)必须改写它来满足您的需求。
I purposely kept this directive simple and straightforward. You may (and probably will) have to reword it to fit your needs.
这篇关于动态添加在NG-重复指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!