最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular precedence of ng-repeat with filter and ng-if on the same element - Stack Overflow

programmeradmin5浏览0评论

If there's a ng-if and a ng-repeat with a filter on the same element the filter gets called once even if the ng-if is hiding the element.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $timeout) {
  $timeout(function() {
    $scope.list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  }, 2000);
});

app.filter('crashyFilter', function() {
  return function(list) {
    return list.map(function(item) {
      return item + 1;
    });
  };
});
<body ng-controller="MainCtrl">
  <div ng-if="list" ng-repeat="item in list | crashyFilter">
    {{item}}
  </div>
</body>

In the browser console you can see that the map call fails once because the list parameter is undefined. I made a plunker with it here.

Anyone knows why this is happening?

If there's a ng-if and a ng-repeat with a filter on the same element the filter gets called once even if the ng-if is hiding the element.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $timeout) {
  $timeout(function() {
    $scope.list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  }, 2000);
});

app.filter('crashyFilter', function() {
  return function(list) {
    return list.map(function(item) {
      return item + 1;
    });
  };
});
<body ng-controller="MainCtrl">
  <div ng-if="list" ng-repeat="item in list | crashyFilter">
    {{item}}
  </div>
</body>

In the browser console you can see that the map call fails once because the list parameter is undefined. I made a plunker with it here.

Anyone knows why this is happening?

Share Improve this question edited Mar 21, 2016 at 15:51 toskv asked Oct 9, 2015 at 21:32 toskvtoskv 31.7k7 gold badges75 silver badges76 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

After some digging about in the angular codebase I found out the reason.

The ng-repeat directive has priority 1000 while ng-if has priority 600.

The angular documentation for the $pile service states that if directives are set on the same element they are piled in decreasing priority order, thus ng-repeat gets piled before ng-if.

That explains why the the filter would also get called before ng-if can disable the element.

Filter came handy to solve the issue for me[AngularJS].

<option ng-repeat="list in lists | filter:{Location:{event: 1}}" value="{{list.Location.id}}">

Where i wanted to show element's where event is 1.

发布评论

评论列表(0)

  1. 暂无评论