Reputation: 4984
I have a jsFiddle here - http://jsfiddle.net/GRw64/
I'm new to Angularjs so still finding my feet
My example is a simple ng-init of customer names.
An input field and a ng-repeat to filter the name in the input field against the customer names.
If you type a name in the input field the ng-repeat filters the list to show that name.
If I type Chris the name 'Chris Dave' and 'Chris' appear in the list.
If I change to 'Chris Dave', 'Chris Dave' is still showing in the list but 'Chris' disappears
How can I get a return with all the results that match at least one word in the search.
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
</head>
<body ng-app="" data-ng-init="customers=[{name:'Chris Dave'},{name:'Chris'},{name:'John'},{name:'Paul'}]">
<div class="container">
Names:
<br />
<input type="text" data-ng-model="name" />
<br />
<ul>
<li data-ng-repeat="cust in customers | filter:name">{{ cust.name }}</li>
</ul>
</div>
</body>
</html>
Upvotes: 0
Views: 2811
Reputation: 6066
You can also provide a function to the filter
filter of Angular:
ng-repeat="cust in customers | filter:filterByName"
Then you have to define the function in your controller:
$scope.filterByName = function(customer) {
if(!$scope.name) {
return true;
} else {
var keywords = $scope.name.toLowerCase().split(' ');
for(var i in keywords){
var k = keywords[i];
if (customer.name.toLowerCase().indexOf(k) >= 0) {
return true;
}
}
return false;
}
}
Upvotes: 2
Reputation: 54524
Suppose you treat the space-separated keywords as OR relationship, you can create a custom filter to achieve what you need like this:
var app = angular.module('myApp', []);
app.filter('myFilter', function () {
return function (names, keyword) {
var listToReturn = [];
if (keyword === undefined) return names;
var keywords = keyword.toLowerCase().split(' ');
angular.forEach(names, function (name) {
for(var i in keywords){
var k = keywords[i];
if (name.name.toLowerCase().indexOf(k) >= 0) {
listToReturn.push(name);
break;
}
}
});
return listToReturn;
};
});
Upvotes: 1