gpt4 book ai didi

javascript - 如何将变量注入(inject)子指令

转载 作者:行者123 更新时间:2023-11-30 05:47:43 26 4
gpt4 key购买 nike

对于以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com