Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - Using ng-class with a function call - called multiple times

I'm using Ionic and want to dynamically change the background colour of each item in an <ion-list> based on the data. I thought I'd do this by way of a function call to return the correct class

<ion-list>
  <ion-item ng-repeat="singleCase in allCases" ng-class="getBackgroundColour(singleCase)" class="item-avatar">
    <h2>{{singleCase.date}}</h2>
    <p>{{singleCase.caseType}}</p>
  </ion-item>
</ion-list>

This is the controller at present

  .controller('AllCasesCtrl', ['$scope', '$log', 'dummyData', function($scope, $log, dummyData) {
    $scope.allCases = dummyData.cases;

    $scope.getBackgroundColour = function(singleCase){

      $log.log("getBackgroundColour called...singleCase type: " + singleCase.speciality);

      var colourMap = {
        speciality1: "speciality1Class",
        speciality2: "speciality2Class",
        speciality3: "speciality3Class"
      };

      return colourMap[singleCase.speciality];
    };

  }])

On checking the console, the getBackgroundColour() function is being called 7 times for each <ion-item> in the list. Why is this, and should I avoid using a function call in ng-class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

AngularJS works with dirty checking: it needs to call the function each cycle to be sure that it doesn't return a new value and that the DOM doesn't need to be updated.

It's part of the typical process of the framework, and calling a function as simple as yours shouldn't have any negative performance impact. Readability and testability of your code is far more important here, so keep the logic in your controller.

One simple things to do, however, is simply to move the declaration of colourMap, which is a constant, outside of your function:

var colourMap = {
    speciality1: "speciality1Class",
    speciality2: "speciality2Class",
    speciality3: "speciality3Class",
};

$scope.getBackgroundColour = function(singleCase) {
  return colourMap[singleCase.speciality];
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...