2016-12-29 79 views
0

在我ng-repeat名單,我從一個對象數組$scope.toBuy顯示對象元素的元素:AngularJS只顯示符合特定條件

$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 
      } 
     ]; 

,我初始化所有元素的boughtfalse。如何在ng-repeat列表中顯示僅顯示bought字段中具有false值的元素?我嘗試這樣做:

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

但加載頁面時顯示沒有的元素。如果我刪除了過濾器,則會顯示整個列表,這意味着我錯誤地應用了過濾器。

回答

2

您正在使用無效的JavaScript對象語法{item.bought===false }

更改爲

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

DEMO

0

使用NG-IF(或NG-顯示):

<div ng-repeat="item in toBuy"> 
    <div ng-if="item.bought===false"> 
     Buy 10 {{item.quantity}} {{item.name}} 
    </div> 
</div> 
+0

我知道這種方法。然而,是否有可能修復過濾器呢? –

0

試試這個:

<li ng-repeat="item in toBuy | filter:item.bought==false"> 

或者

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

會的工作,二是更好的方式來實現這一目標。

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=[{ 
 
    \t "name": "cookies", 
 
    \t "quantity": 0, 
 
    \t "bought": true 
 
    }, { 
 
    \t "name": "water", 
 
    \t "quantity": 0, 
 
    \t "bought": true 
 
    }, { 
 
    \t "name": "bananas", 
 
    \t "quantity": 0, 
 
    \t "bought": true 
 
    }, { 
 
    \t "name": "milk", 
 
    \t "quantity": 0, 
 
    \t "bought": false 
 
    }, { 
 
    \t "name": "coconut", 
 
    \t "quantity": 0, 
 
    \t "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>

+0

我相信你可以在它們周圍定義帶或不帶「」的對象字段。 (http://www.w3schools.com/js/js_object_definition.asp)。順便說一下你用什麼工具來檢測JSON失效? –