我怎样才能在angularJs中按类名计算?
我尝试过:
$scope.numItems = function() {
$window.document.getElementsByClassName("yellow").length;
};
Run Code Online (Sandbox Code Playgroud)
Plunkr:http://plnkr.co/edit/ndCqpZaALfOEiYieepcn?p =preview
您已正确定义了您的功能,但在显示其结果时出错:应该是......
<p>{{numItems()}}</p>
Run Code Online (Sandbox Code Playgroud)
...而不是平原{{numItems}}.您希望显示函数的返回值,而不是函数本身(这没有意义),这就是您应该遵循标准JS语法进行函数调用的原因.
请注意,您也可以将参数发送到此表达式中:例如,我已经重写了这样的方法:
$scope.numItems = function(className) {
return $window.document.getElementsByClassName(className).length;
};
Run Code Online (Sandbox Code Playgroud)
...然后在模板中制作了三个不同的计数器:
<p>Yellow: {{numItems('yellow')}}</p>
<p>Green: {{numItems('green')}}</p>
<p>Red: {{numItems('red')}}</p>
Run Code Online (Sandbox Code Playgroud)
但这是真正的问题:numItems()在一个视图中使用的结果基于DOM遍历 - 换句话说,在另一个视图上.这不仅违背了Angular哲学,而且往往会破裂.事实上,自从这次提交以来它已经破了,就像1.3.0一样:
现在,即使不使用ngAnimate模块,如果
$rootScope处于摘要中,也会延迟类操作.这有助于减少IE11等浏览器中的jank.
请参阅,摘要后应用类中的更改- 然后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;
};
Run Code Online (Sandbox Code Playgroud)
的index.html
<p ng-class="getColor('toggle')">{{name}}</p>
<!-- ... -->
<p ng-repeat="color in ['Yellow', 'Green', 'Red']"
ng-bind="color + ' ' + countColor(color.toLowerCase())">
Run Code Online (Sandbox Code Playgroud)
演示.
| 归档时间: |
|
| 查看次数: |
10443 次 |
| 最近记录: |