【问题标题】:AngularJs get count of element by class nameAngularJs 按类名获取元素计数
【发布时间】:2016-07-02 00:05:28
【问题描述】:

如何在 angularJs 中按类名计算元素?

我试过了:

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

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

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    你已经正确定义了你的函数,但是在显示它的结果时犯了一个错误:它应该是……

    <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() 结果,在一个 View 中使用,是基于 DOM 遍历的 - 换句话说,在另一个 View 上。这不仅与一般的 Angular 哲学背道而驰,而且往往会破裂。事实上,它从 this commit 开始就中断了,与 1.3.0 一样古老:

    现在,即使不使用 ngAnimate 模块,如果 $rootScope 在 在摘要中,类操作被推迟。这有助于 减少IE11等浏览器的卡顿。

    看,类的变化是在 摘要之后应用的 - 那是在评估 numItems() 之后,因此 @Thirumalaimurugan 提到的演示延迟。

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

    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.

    【讨论】:

    • 在 angularjs 1.4.8 版本中它没有按预期工作?请检查plnkr.co/edit/g6fa6waeg0HSH29aYgnN?p=preview
    • Here 我(在某种程度上)修复了它。总的来说,OP 的意图——在视图中而不是在模型中跟踪变化——从一开始就不是一个好主意,这就是为什么当 AngularJS 团队优化对类变化的处理时它很容易被打破。稍后我会用解释更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2015-11-04
    • 2016-06-18
    相关资源
    最近更新 更多