在函数调用中使用 ng-class - 多次调用 [英] Using ng-class with a function call - called multiple times

查看:25
本文介绍了在函数调用中使用 ng-class - 多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ionic 并希望根据数据动态更改 中每个项目的背景颜色.我以为我会通过函数调用来返回正确的类

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>

这是目前的控制器

  .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];
    };

  }])

在检查控制台时,getBackgroundColour() 函数为列表中的每个 调用了 7 次.这是为什么,我应该避免在 ng-class 中使用函数调用吗?

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?

推荐答案

AngularJS 使用 脏检查:它需要调用函数每个周期以确保它不会返回新值并且不需要更新DOM.

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.

然而,要做的一件简单的事情就是将 colourMap 的声明移动到您的函数之外,它是一个常量:

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];
};

这篇关于在函数调用中使用 ng-class - 多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆