ng-repeat
列表中的我正在显示对象数组$scope.toBuy
中的对象元素:
$scope.toBuy=[
cookies={
name:'cookies',quantity:0,bought:false
},
water={
name:'water',quantity:0,bought:false
},
bananas={
name:'bananas',quantity:0,bought:false
},
milk={
name:'milk',quantity:0,bought:false
},
coconut={
name:'coconut',quantity:0,bought:false
}
];
我将所有元素的bought
字段初始化为false
。如何在仅显示ng-repeat
字段中false
值的元素的bought
列表中显示?我试过这个:
<ul>
<li ng-repeat="item in toBuy | filter:{item.bought===false }">Buy 10 {{item.quantity}} {{item.name}} <button class="btn btn-default" ng-click="btnOnClick(item.name)"> Bought</button></li>
</ul>
但加载页面时没有显示任何元素。如果我删除了过滤器,则显示整个列表,这意味着我错误地应用了过滤器。
答案 0 :(得分:2)
您使用的是无效的javascript对象语法{item.bought===false }
更改为
ng-repeat="item in toBuy | filter:{bought:false }"
的 DEMO 强>
答案 1 :(得分:1)
您的JSON
不是 valid JSON
。
试试 valid JSON
:
[{
"name": "cookies",
"quantity": 0,
"bought": true
}, {
"name": "water",
"quantity": 0,
"bought": true
}, {
"name": "bananas",
"quantity": 0,
"bought": true
}, {
"name": "milk",
"quantity": 0,
"bought": false
}, {
"name": "coconut",
"quantity": 0,
"bought": false
}]
工作演示:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.toBuy=[{
"name": "cookies",
"quantity": 0,
"bought": true
}, {
"name": "water",
"quantity": 0,
"bought": true
}, {
"name": "bananas",
"quantity": 0,
"bought": true
}, {
"name": "milk",
"quantity": 0,
"bought": false
}, {
"name": "coconut",
"quantity": 0,
"bought": false
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<ul>
<li ng-repeat="item in toBuy | filter : {bought:false}">Buy 10 {{item.quantity}} {{item.name}} <button class="btn btn-default" ng-click="btnOnClick(item.name)"> Bought</button></li>
</ul>
</div>
答案 2 :(得分:0)
使用ng-if(或ng-show):
<div ng-repeat="item in toBuy">
<div ng-if="item.bought===false">
Buy 10 {{item.quantity}} {{item.name}}
</div>
</div>
答案 3 :(得分:0)
试试这个:
<li ng-repeat="item in toBuy | filter:item.bought==false">
或者
<li ng-repeat="item in toBuy | filter:{bought:false}">
会工作,第二种是实现这一目标的更好方法。