使用$filter
获取具有指定属性的数组元素的长度时遇到问题。属性state
可以是0
,1
和-1
。我得到$filter
的子数组,然后检查length
。它不适用于state = 1
。似乎过滤器也使用state = -1
的元素。这是一个错误还是我需要以不同的方式设置过滤器?
我提供了一个片段来展示效果。提前谢谢。
angular.module ('app', []).controller ('ctrl', function ($scope, $filter) {
$scope.data = [
{ state: 0 },
{ state: 1 },
{ state: -1 }
];
$scope.out1 = $filter ('filter')($scope.data, { state: 0 }).length; // =1
$scope.out2 = $filter ('filter')($scope.data, { state: 1 }).length; // =2 <== THATS NOT RIGHT
$scope.out3 = $filter ('filter')($scope.data, { state: -1 }).length; // =1
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div>Elements with state=0 --> <strong ng-bind="out1"></strong></div>
<div>Elements with state=1 --> <strong ng-bind="out2"></strong></div>
<div>Elements with state=-1 --> <strong ng-bind="out3"></strong></div>
</div>
&#13;
答案 0 :(得分:1)
AngularJS将state
值视为字符串("-1".indexOf("1") != -1
),因此只需向strict
添加第三个filter
参数:
$scope.out2 = $filter('filter')($scope.data, { state: 1 }, true).length;