按属性对象的属性进行筛选

时间:2014-06-17 20:44:55

标签: javascript angularjs filter angularjs-ng-repeat jsfiddle

我有一组对象设置如下:

$scope.people = [{name:
                  {last:"Doe", first:"John"}},
                 {name:
                  {last:"Smith", first:"Joe"}}];

我试图通过姓氏的文本框进行实时过滤。

这里是jsfiddle:http://jsfiddle.net/HB7LU/4287/

任何帮助都会很好。谢谢!

编辑:抱歉,我输了错误的jsfiddle

2 个答案:

答案 0 :(得分:1)

以你的小提琴作为起点,我会说:

HTML

<div ng-controller="MyCtrl">    
  <input ng-model="search" ng-init="search = ''" placeholder="enter search" />
  <div ng-repeat="person in people | filter:{name.last: search}">
    {{ person | json }}
  </div>
</div>

JS

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.people = [{ name: { last: 'Doe', first: 'John' } },
                     { name: { last: 'Smith', first: 'Joe' } }];

}

以下是plunker http://plnkr.co/edit/W46Fkj

答案 1 :(得分:0)

所以创建一个过滤器!

建立现有代码:

myApp.filter("search", function() {
    return function(people, startPhrase) {
        if(!startPhrase) {
            return people;   
        }
        var filtered = [];
        for(obj in people) {
            if(people[obj].name.last.indexOf(startPhrase) == 0) {
                filtered.push(people[obj]);
            }
        }
        console.log(filtered);
        return filtered;
    }
});

现在,您可以在HTML中的任何位置使用名为“搜索”的过滤器。这样称呼:

<div ng-controller="MyCtrl">
    <input ng-model="search.name.last"/>
    <div ng-repeat="person in people | search:search.name.last">
        {{person.name.last}}, {{person.name.first}}
    </div>
</div>