当指令为其模板使用函数时,如何从传递到指令的 ng-repeat
访问对象?
我在指令中设置了以下ng-repeat
:
<my-directive ng-repeat="item in list.contents" item="item"></my-directive>
app.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
item: '='
},
template: function (element, attrs) {
// pseudo-code
if (item.type == "typeA")
return '<li>{{ item }} one type</li>';
else
return '<li>{{ item }} another type</li>';
}
};
});
在模板中,{{ item }}
工作正常,但我不知道如何引用 item
作为传入的对象ng-repeat
。使用 attrs
我可以从标签中获取值,但该值只是一个字符串。
当type
被传递给ng-repeat
时,我可以将它作为对象获取吗?
最佳答案
我认为你必须改变你的方法。无法从模板函数访问范围。您可以在模板本身中使用 ng-if
,而不是在模板函数中使用 if
语句。
例如:
指令
app.directive('myDirective',function() {
return {
restrict: 'E',
scope: { item: '='},
template: '<div ng-if="item.type==\'one\'">' +
'{{item.name}}' +
'</div>' +
'<div ng-if="item.type==\'two\'">' +
'{{item.name}}' +
'</div>'
}
});
HTML
<body ng-app="app" ng-controller='ctrl'>
<my-directive ng-repeat="item in items" item="item"></my-directive>
</body>
Controller
app.controller('ctrl', function($scope) {
$scope.items = [];
$scope.items.push({type:'one', name: 'One'});
$scope.items.push({type:'two', name: 'Two'});
});
关于javascript - 使用函数作为模板重复 AngularJS 指令中访问 `$scope`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521080/