AngularJS仅显示满足特定条件的元素

时间:2016-12-29 03:07:52

标签: angularjs

我在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>

但加载页面时没有显示任何元素。如果我删除了过滤器,则显示整个列表,这意味着我错误地应用了过滤器。

4 个答案:

答案 0 :(得分:2)

您使用的是无效的javascript对象语法{item.bought===false }

更改为

ng-repeat="item in toBuy |  filter:{bought:false }"

DEMO

答案 1 :(得分:1)

您的JSON不是 valid JSON

enter image description here

试试 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}">

会工作,第二种是实现这一目标的更好方法。