这很难说,但是:
我有一个名为users
的集合
每个用户都有3个属性:id, name, skill
。
{
_id: 1,
name: 'frank young',
skill: 'java'
},
我有1个表单按回车键收集搜索结果。
<form ng-submit="pushToNewArry(searchTerm)">
<input type="text" ng-model="searchTerm" />
<input type="submit">
</form>
这不是执行此操作的最佳方式
$scope.newUsers = [];
$scope.pushToNewArry = function(msg) {
$scope.trackedUsers.push(msg);
$scope.searchTerm = '';
};
问题:
如何创建一个将在多个搜索字词上运行的过滤器,并根据users
集合与输入值创建匹配的匹配列表。
<ol ng-repeat = "user in users | filter: trackedUsers">
<li class="names"><span>{{$index}}. </span>{{user.name}}</li>
<li class="skills">{{user.skill}}</li>
</ol>
提交后,将保存用户输入并根据搜索的输入值创建users
的新数组。因此,多个匹配值。
更新:
与上面的例子不同,因为我一直在玩它。
答案 0 :(得分:2)
你的意思是this jsfriddle
更新fiddle
更新fiddle2
<div>{{listSearchTerms | json}}</div>
<form ng-submit="saveSearchTerm()">
<input type="text" ng-model="searchTerm" />
<input type="submit">
</form>
<ol ng-repeat = "user in users | filter:filterSearch(searchTerm)">
<li class="names"><span>{{$index}}. </span>{{user.name}}</li>
<li class="skills">{{user.skill}}</li>
</ol>
的Javascript
var app = angular.module('app', []);
//App.directive('myDirective', function() {});
//App.factory('myService', function() {});
app.controller('MainCtrl', function ($scope) {
$scope.users = [
{
_id: 1,
name: 'frank young',
skill: 'java'
},
{
name: 'jeff qua',
skill: 'javascript'
},
{
name: 'frank yang',
skill: 'python'
},
{
name: 'ethan nam',
skill: 'python'
},
{
name: 'ethan nam',
skill: 'javascript'
},
];
$scope.searchTerm = "";
$scope.listSearchTerms = [];
$scope.filterSearch = function (terms) {
return function (item) {
return terms.length < 1 ? true :
terms.reduce(function (lastresult, term) {
return lastresult + (item.name.indexOf(term) > -1 || item.skill.indexOf(term) > -1);
}, 0) > 0;
}
};
$scope.saveSearchTerm = function () {
$scope.listSearchTerms.push($scope.searchTerm);
$scope.searchTerm = "";
}
});