在用函数作为模板的重复AngularJS指令中访问' $scope '
Access `$scope` in Repeating AngularJS Directive with Function as Template
我怎么能访问一个对象从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>'
}
});