[英]Filter by object property in Angularjs
我正在嘗試在AngularJS中創建一個簡單的過濾器,該過濾器將通過我的JSON進行過濾:first_name,last_name和phone_number,但是我不確定如何在JSON中引用特定的屬性來創建HTML下拉列表。
HTML
<div ng-app="instantsearch">
<div ng-controller="instantSearchCtrl">
<input type="text" class="search" ng-model="searchString" placeholder="Enter your search terms" />
<select class="data-ctrl" >
<option ng-repeat="i in items | filter:searchString" value="@{{ i.clientid }}">@{{ i.first_name }} @{{ i.last_name }}</option>
</select>
</div>
</div>
JSON
{"clients":
[
{"clientid":"1","first_name":"myfirst","last_name":"client","phone_number":"","email":""},
{"clientid":"2","first_name":"mysecond","last_name":"client","phone_number":"","email":""},
{"clientid":"3","first_name":"mythird","last_name":"client","phone_number":"","email":""},
{"clientid":"4","first_name":"myfourth","last_name":"client","phone_number":"","email":""}
]}
JS
var app = angular.module('instantsearch',[]);
app.controller('instantSearchCtrl',function($scope,$http){
$http.get('/api/clients').success(function(data, status, headers, config) {
$scope.items = data.data;
}).error(function(data, status, headers, config) {
console.log("No data found..");
});
});
app.filter('searchFor', function(){
return function(arr, searchString){
if(!searchString){
return arr;
}
var result = [];
searchString = searchString.toLowerCase();
angular.forEach(arr, function(item){
if(item.first_name.toLowerCase().indexOf(searchString) !== -1){
result.push(item);
}
});
return result;
};
});
您的問題實際上不在於您如何配置下拉列表,而在於控制器代碼。 根據您的JSON,應為:
$scope.items = data.clients;
但是,您可以做的另一項改進是使用ngOptions而不是ngRepeat。 因此下拉列表將變為
<select class="data-ctrl"
ng-model="client"
ng-options="i.clientid as ('@' + i.first_name + ' @' + i.last_name) for i in items | filter:searchString">
</select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.