【发布时间】:2016-07-02 00:05:28
【问题描述】:
如何在 angularJs 中按类名计算元素?
我试过了:
$scope.numItems = function() {
$window.document.getElementsByClassName("yellow").length;
};
【问题讨论】:
标签: angularjs
如何在 angularJs 中按类名计算元素?
我试过了:
$scope.numItems = function() {
$window.document.getElementsByClassName("yellow").length;
};
【问题讨论】:
标签: angularjs
你已经正确定义了你的函数,但是在显示它的结果时犯了一个错误:它应该是……
<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>
但真正的问题是: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.
【讨论】: