在init上过滤JSON数据

时间:2014-10-07 13:48:04

标签: json angularjs angularjs-filter

这是我的JSON对象:

{
Stores: [
{
    Name: "Store #1",
    DealerType: "Office"
},
{
    Name: "Store #2",
    DealerType: "Office"
},
{
    Name: "Store #3",
    DealerType: "Office"
},
{
    Name: "Store #4",
    DealerType: "Headquater"
},
]
}

这是我的观点:

<select id="dealerType">
     <option value="">All</option>
     <option value="Office">Office</option>
     <option value="Headquater">Headquaters</option>
</select>
<ul>
    <li ng-repeat="store in stores | filter:dealerType">{{store.Name}}</li>
</ul>

我想只在页面加载中显示DealerType: "Headquater"的一个商店,并且仍然可以使用<select> - 元素

中的过滤功能

我尝试将ng-repeat更改为:ng-repeat="store in stores | filter:{DealerType: 'Headquater'} | filter:dealerType"。 这会根据DealerType进行过滤,但在更新“dealerType”选择时不会更改。

2 个答案:

答案 0 :(得分:0)

两件事:

使用ng-model

确保将select设置为模型的一部分,

<select ng-model="dealerType">...</select>

过滤表达式

使用适当的过滤器表达式将您的属性定位到上面定义的模型。

<li ng-repeat="store in stores | filter:{'DealerType': dealerType}:true">{{store.Name}}</li>

查看此similar answer

这是一个working plunk

答案 1 :(得分:0)

http://jsbin.com/fuwaki/1/edit

<div ng-app="app">
    <div ng-controller="fCtrl">
      <select id="dealerType" ng-model="dealerType">
     <option value="">All</option>
     <option value="Office">Office</option>
     <option value="Headquater">Headquaters</option>
</select>
<ul>
    <li ng-repeat="store in stores | filter:dealerType">{{store.Name}}  | {{store.DealerType}}</li>
</ul>
    </div>
    </div>


var app = angular.module('app',[]);

app.controller('fCtrl', function($scope){

   $scope.stores= [{
     Name: "Store #1",
     DealerType: "Office"
 }, {
     Name: "Store #2",
     DealerType: "Office"
 }, {
     Name: "Store #3",
     DealerType: "Office"
 }, {
     Name: "Store #4",
     DealerType: "Headquater"
 } ];

$scope.dealerType = 'Headquater'
});