ng-if being called more times than it should

扶醉桌前 提交于 2019-11-28 01:58:44
Duncan

Your ng-if will be called on every digest loop. The problem is that it contains an expression involving a function call. Angular has no way to know when the result of the expression might change, so it calls it every time.

A better option would be to set a flag in each of the channels and use ng-if to just test the relevant flag. Then you just have to update the flags whenever $scope.activeCategory changes which you can either do with code where you set the category or using $scope.$watch() to trigger it automatically.

e.g.

$scope.setCategory = function (name) {
  $scope.activeCategory = name;
  for (var index=0; index < $scope.channels.length; index++) {
      $scope.channels[index].hasCategory = hasCategory($scope.channels[index].category, name);
  }
};

function hasCategory(categoryNameArray, name) {
  console.log('thisisbeingcalled');
  var e = _.indexOf(categoryNameArray, name);
  if (e === -1) {
    return false;
  } else {
    return true;
  }
}

Then in your template:

<md-card flex="15" flex-xs="40" class="slide-up" layout="column"
    ng-repeat="channel in channels | orderBy: 'number' | filter: queryname"
    ng-if="channel.hasCategory"
    ng-init="channel.edit = false">
  <md-card-header ng-show="channel.edit == false">
    <img ng-src="{{channel.logo}}" alt="">
  </md-card-header>
  <md-card-header-text ng-show="channel.edit == false">
    <span class="md-subhead dark-blue" layout="row" layout-align="center" layout-margin>{{channel.number}}</span>
  </md-card-header-text>
</md-card>

should be more efficient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!