当指令使用函数作为模板时,如何从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
吗?
答案 0 :(得分:1)
我认为你必须修改你的方法。无法从模板功能访问范围。您可以在模板本身中使用if
,而不是在模板函数中使用ng-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>
<强>控制器强>
app.controller('ctrl', function($scope) {
$scope.items = [];
$scope.items.push({type:'one', name: 'One'});
$scope.items.push({type:'two', name: 'Two'});
});