我试图在ng-repeat中使用$parse
指令属性的表达式。
这是一个简单的HTML:
<body ng-app="hello" ng-controller="control">
<div ng-repeat="a in array" my-dir="a.one == 1"></div>
</body>
和Angular指令:
angular.module('hello', [])
.controller('control', function($scope){
$scope.array = [{
one: 1,
two: 2
},
{
one: 3,
two: 4
}];
})
.directive('myDir', function($parse){
return {
restrict: 'A',
link: function(scope, elem, attrs){
var hash = $parse(attrs.myDiv);
// I would like a way of evaluating this expression
// without having to use things like my-dir="array[$index].item == 1"
// just like one would do with other angular directives.
console.log(hash(scope)); // This is undefined, because a.one can not be found in scope.
},
};
});
执行此操作的问题是$parse
正在使用scope
查找a.one
属性,而且显然不存在。
我可以做my-dir="array[$index].one == 1"
但对指令的用户来说并不直观(他们必须考虑他们调用指令的范围)。