AngularJs按类名获取元素数

时间:2013-09-16 01:01:44

标签: angularjs

如何在angularJs中按类名计算?

我尝试过:

$scope.numItems = function() {
    $window.document.getElementsByClassName("yellow").length;
};

Plunkr:http://plnkr.co/edit/ndCqpZaALfOEiYieepcn?p=preview

1 个答案:

答案 0 :(得分:7)

您已正确定义了您的功能,但在显示其结果时出错:它应该是......

<p>{{numItems()}}</p>

...而不是普通{{numItems}}。您希望显示函数的返回值,而不是函数本身(这是无意义的),这就是为什么您应该遵循标准JS语法进行函数调用的原因。

请注意,您也可以将参数发送到此表达式中:例如,我已经重写了这样的方法:

$scope.numItems = function(className) {
   return $window.document.getElementsByClassName(className).length;
};

...然后在模板中制作了三个不同的计数器:

  <p>Yellow: {{numItems('yellow')}}</p>
  <p>Green: {{numItems('green')}}</p>
  <p>Red: {{numItems('red')}}</p>

Plunker Demo


但这是真正的问题:在一个视图中使用的numItems()结果基于DOM遍历 - 换句话说,在另一个视图上。这不仅违背了Angular哲学,而且往往会破裂。事实上,它已经从this commit开始,与1.3.0相同:

  

现在,即使未使用ngAnimate模块,如果$rootScope处于使用状态   在摘要中,类操作被推迟。这有帮助   在IE11等浏览器中减少jank。

请参阅摘要后类中的更改 - 以及numItems()之后的评估,因此@Thirumalaimurugan提及的演示延迟。

一个快速而肮脏的解决方案是在numItems中使用选择器的另一个属性(在此plunker中,它是data-color)。但我强烈建议你不要这样做。正确的方法是将numItems() - 使用组件呈现的数据添加到模型中。例如:

<强> app.js

// ...
var colorScheme = {
  'toggle':  {true: 'yellow', false: 'red'},
  'toggle2': {true: 'green', false: 'red'},
  'toggle3': {true: 'green', false: 'red'},
  'toggle4': {true: 'red', false: 'green'}
};

$scope.getColor = function getColor(param) {
  return colorScheme[param][$scope[param]];
};

$scope.countColor = function(color) {
  return Object.keys(colorScheme).filter(function(key) {
    return colorScheme[key][$scope[key]] === color;
  }).length;
};

<强>的index.html

<p ng-class="getColor('toggle')">{{name}}</p>
<!-- ... -->

<p ng-repeat="color in ['Yellow', 'Green', 'Red']" 
   ng-bind="color + ' ' + countColor(color.toLowerCase())">

Demo