繁体   English   中英

在Angularjs中按对象属性过滤

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM