我正在尝试创建一个过滤器,它将根据选择框中的选择在表中显示结果。
此外,默认情况下,“城市”选择框将设置为我正在抓取和设置的用户位置ng-init="my.city='${city}'"
。因此,将根据用户位置过滤默认结果。
我遇到的唯一问题是,当用户位置与我的“城市”选择框中的任何值都不匹配时,它应该被重置。即应该选择“选择一个城市”选项,并且所有结果都将显示而不应用任何过滤器。
在我的代码中,如果我选择任何城市,然后尝试选择“选择城市”,则过滤器不会被重置”。
我该如何解决?
这是完整的代码:
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.loc = {
Sydney: 4,
Toronto: 7,
London: 3,
Berlin: 7
};
$scope.country = ['Australia', 'India', 'Germany', 'China', 'Canada', 'United Kingdom'];
$scope.fullData = [{
name: 'ABC',
countryName: 'Germany',
city: 'Berlin'
}, {
name: 'BCD',
countryName: 'India',
city: 'Bangalore'
}, {
name: 'CDE',
countryName: 'Germany',
city: 'Berlin'
}, {
name: 'ABC',
countryName: 'Australia',
city: 'Sydney'
}, {
name: 'DEF',
countryName: 'China',
city: 'Shanghai'
}, {
name: 'CDE',
countryName: 'Germany',
city: 'Berlin'
}, {
name: 'BCD',
countryName: 'Australia',
city: 'Sydney'
}, {
name: 'ABC',
countryName: 'United Kingdom',
city: 'London'
}, {
name: 'ABC',
countryName: 'China',
city: 'Shanghai'
}, {
name: 'DEF',
countryName: 'Canada',
city: 'Toronto'
}, {
name: 'DEF',
countryName: 'India',
city: 'Bangalore'
}, {
name: 'BCD',
countryName: 'Germany',
city: 'Berlin'
}, {
name: 'ABC',
countryName: 'Canada',
city: 'Toronto'
}];
}]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div class="container">
<div ng-app="myApp" ng-controller="myCtrl">
<div class="row">
<div class="col-md-3">
<label>Search Keyword:</label>
<input type="text" class="form-control" ng-model="my.$"/>
</div>
<div class="col-md-3">
<label>Country:</label>
<select class="form-control" ng-model="my.countryName" ng-options="countryName as countryName for countryName in country">
<option value="" selected>Select a country</option>
</select>
</div>
<div class="col-md-3">
<label>City</label>
<select class="form-control" ng-model="my.city" ng-init="my.city='${city}'" ng-options="key as key for (key, value) in loc">
<option value="" selected>Select a city</option>
</select>
</div>
</div>
<hr />
<div class="row">
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Country</th>
<th>City</th>
</tr>
<tr ng-repeat="item in fullData | filter: my">
<td>{{item.name}}</td>
<td>{{item.countryName}}</td>
<td>{{item.city}}</td>
</tr>
</table>
</div>
</div>
</div>