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

后端 未结 2 1281
一个人的身影
一个人的身影 2020-12-16 13:23

I\'m using Ionic and want to dynamically change the background colour of each item in an based on the data. I thought I\'d do this by way of a

相关标签:
2条回答
  • 2020-12-16 13:58

    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];
    };
    
    0 讨论(0)
  • 2020-12-16 14:02

    Your way is fine as long as your list is not some huge size. That being said if you are using angular 1.3 and you want to lower the number of calls you can change your ng-class to ng-class="::getBackgroundColour(singleCase)". This applies one time binding so once the value is stable it will not check again. This would most likely mean two calls per item.

    0 讨论(0)
提交回复
热议问题