在Angular 1.4.5中的ng-repeat内使用$ parse in指令评估表达式

时间:2015-11-05 13:47:21

标签: javascript angularjs parsing angularjs-ng-repeat directive

我试图在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"但对指令的用户来说并不直观(他们必须考虑他们调用指令的范围)。

1 个答案:

答案 0 :(得分:0)

有拼写错误 - myDiv而不是myDirhttp://plnkr.co/edit/rwoUXjxmvmdTp3OIE4Yo?p=preview