I have a ng-repeat filtered by the parameters city & first_name , as in the example:
vm.search = {
"city": "D.C.",
"first_name": "Chu"
};
<li ng-repeat="item in user | filter: search">...
var appname = 'app'; var dependencies = []; angular.module(appname, dependencies); var app = angular.module(appname); var userC = function ($scope) { var vm = $scope; vm.search = { "city": "DC", "first_name": "Chu" }; vm.user = [ { "id": 1, "first_name": "Chuck", "last_name": "Norris", "city": "Washington DC", "languages": [ { "id": "41", "name": "English" }, { "id": "73", "name": "Japanese" } ] } ]; }; app.controller('userC', userC);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <ul ng-app="app" ng-controller="userC"> <li ng-repeat="item in user | filter: search track by item.id"> {{ item.first_name }} {{ item.last_name }} </li> </ul>
But now I need to filter by languages which is an array of objects:
vm.search = {
"languages": [
{
"name": "Japanese"
}
]
};
<li ng-repeat="item in user | filter: search">...
var appname = 'app'; var dependencies = []; angular.module(appname, dependencies); var app = angular.module(appname); var userC = function ($scope) { var vm = $scope; vm.search = { "languages": [ { "name": "Japanese" } ] }; vm.user = [ { "id": 1, "first_name": "Chuck", "last_name": "Norris", "city": "Washington DC", "languages": [ { "id": "41", "name": "English" }, { "id": "73", "name": "Japanese" } ] } ]; }; app.controller('userC', userC);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <ul ng-app="app" ng-controller="userC"> <li ng-repeat="item in user | filter: search track by item.id"> {{ item.first_name }} {{ item.last_name }} </li> </ul>
As you can see, there are no results because the default filter doesn't do the job.
Can someone help me achieving a filter that suits this last case?
Both examples are here:
You have to declare languages
as an object:
vm.search = {
"languages":
{
"name": "Japanese"
}
};
Here's the codepen.
Update after comment: if you want a more complex filter, you can use a function instead of an object. Angular will call Array.prototype.filter() on your user
array, so your function could be defined this way:
var allowedLanguages = [
"Japanese",
"Brazilian Portuguese"
];
vm.search = function(item) {
for (var i = 0; i < item.languages.length; i++) {
if (allowedLanguages.indexOf(item.languages[i].name) !== -1) {
return true;
}
}
return false;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.