作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
对于以下 angularjs 指令:
app = angular.module('ngApp');
app.value('objects', [
{id: 1, name: 'Jane Doe', active: true},
{id: 2, name: 'Test Biz', active: false},
{id: 3, name: 'Another Business', active: false}
]);
app.directive('myDirective', function (objects) {
return {
template: '<ul></ul>',
replace: true,
compile: function(element, attrs) {
for(var i=0;i<objects.length;i++) {
element.append('<div other-directive object={{object}}></div>');
}
}
};
})
.directive('otherDirecctive', function() {
return {
template: '<li>{{object.name}}',
replace: true,
scope: { object: '=' }
});
还有这段 html:
<div my-directive></div>
如何将每个对象传递给子指令?是否有更好的总体方式来构建此代码?
最佳答案
我建议只使用一个指令并在模板中使用 ng-repeat
:
app.directive('myDirective', function (objects) {
return {
link: function(scope,element,attrs){
scope.objects = objects;
},
template: '<ul><li ng-repeat="o in objects">{{o.name}}</li></ul>'
};
});
但是如果你仍然想使用第二个指令,你可以按原样使用,只需将第一个的模板更改为:
'<ul><li ng-repeat="o in objects" other-directive object="o"></li></ul>'
演示: Here is a fiddle
关于javascript - 如何将变量注入(inject)子指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16949749/
我是一名优秀的程序员,十分优秀!