How can I dynamically limit data showing in an ng-repeat? - angularjs

I have this ng-repeat that I show split over three rows here for clarity:
ng-repeat="row in phs.phrasesView =
(phs.phrases | orderBy:phs.phrasesOrderBy[phs.phrasesOrderById]
.key:phs.phrasesSortDirectionId == 1)">
On my form I have a field phs.keywordRange
Is there a way that I can make it so the rows returned are filtered as follows:
When phs.keywordRange is null or empty string, all rows are shown
When phs.keywordRange is A then only rows where row.keyword starts with A are shown
When phs.keywordRange is ABC then only rows where row.keyword starts with ABC are shown

Make your own filter, like this fiddle.
Changing the $scope.keywordRange will update the list accordingly.
as shortcut:
.filter('keywordRange', function() {
return function(value, keyword) {
var out = [];
if(!keyword) {
return value;
}
for(var i = 0; i < value.length; i++) {
if(value[i].startsWith(keyword)){
out.push(value[i]);
}
}
return out;
};
});
function MyCtrl($scope) {
$scope.keywordRange = 'ti';
$scope.lines = [
'rest1', 'rest2', 'tiago', 'pedro', 'america'
];
}
and the html
<div ng-controller="MyCtrl">
<div ng-repeat="line in lines | keywordRange:keywordRange">
<p>{{line}}</p>
</div>
</div>

Related

Angularjs Filter by an Array of values

i've checqued this :
AngularJS filter based on array of strings?
But i've still got difficulties to know how to do :
My data model is this, they are footballers :
$scope.footballers = [
{'identifiant':1,'prenom':'Jean','nom':'Valjean','categorie':1,'ville':'Détroit','age':12,'date_embauche':'','salaire':25,'photo':'1.jpg','vitesse':55,'agilite':3,'deduction':25,'choisi':false},
{'identifiant':2,'prenom':'Aziz','nom':'Jojo','categorie':2,'ville':'Paris','age':14,'date_embauche':'','salaire':25,'vitesse':57,'agilite':31,'deduction':25,'choisi':false},
{'identifiant':3,'prenom':'Thierry','nom':'Goubert','categorie':1,'ville':'Paris','age':17,'date_embauche':'','salaire':28,'photo':'2.jpg','vitesse':45,'agilite':3,'deduction':2,'choisi':false},
{'identifiant':4,'prenom':'Roland','nom':'Grondin','categorie':2,'ville':'Paris','age':14,'date_embauche':'','salaire':25,'vitesse':5,'agilite':34,'deduction':2,'choisi':false},
{'identifiant':5,'prenom':'Gogok','nom':'Rodolphe','categorie':1,'ville':'Paris','age':17,'date_embauche':'','salaire':28,'photo':'3.jpg','vitesse':68,'agilite':75,'deduction':2,'choisi':false},
{'identifiant':6,'prenom':'Thierry','nom':'Chalamerto','categorie':1,'ville':'Paris','age':17,'date_embauche':'','salaire':28,'vitesse':55,'agilite':57,'deduction':75,'choisi':false},
{'identifiant':7,'prenom':'Gawivk','nom':'Gonzogues','categorie':2,'ville':'Paris','age':14,'date_embauche':'','salaire':25,'vitesse':10,'agilite':44,'deduction':2,'choisi':false},
{'identifiant':8,'prenom':'Thomas','nom':'Choubal','categorie':1,'ville':'Paris','age':12,'date_embauche':'','salaire':28,'vitesse':5,'agilite':3,'deduction':2,'choisi':false}
];
Now, I would like to display only the footballer who has the identifiant 2,3 and 8 for example.
Let's say I 've got this array :
var iwanttofilter = [2,3,8];
How could i do to filter with angularJs, firstly, in my ng-repeat, and secondly directly into my controller ?
Thank you.
In pure angular way
var filteredList = $filter('filter')($scope.footballers, function (i) {
return (i.identifiant === 2 || i.identifiant === 3 || i.identifiant === 8);
});
you can create a custom filter like this
.filter('cust',function(){
var iwanttofilter = [2,3,8];
return function(item){
return item.filter(o=>iwanttofilter.find(k=> o.identifiant == k))
}
})
in here array will filter according the iwanttofilter array and return the result
Demo
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.footballers = [
{'identifiant':1,'prenom':'Jean','nom':'Valjean','categorie':1,'ville':'Détroit','age':12,'date_embauche':'','salaire':25,'photo':'1.jpg','vitesse':55,'agilite':3,'deduction':25,'choisi':false},
{'identifiant':2,'prenom':'Aziz','nom':'Jojo','categorie':2,'ville':'Paris','age':14,'date_embauche':'','salaire':25,'vitesse':57,'agilite':31,'deduction':25,'choisi':false},
{'identifiant':3,'prenom':'Thierry','nom':'Goubert','categorie':1,'ville':'Paris','age':17,'date_embauche':'','salaire':28,'photo':'2.jpg','vitesse':45,'agilite':3,'deduction':2,'choisi':false},
{'identifiant':4,'prenom':'Roland','nom':'Grondin','categorie':2,'ville':'Paris','age':14,'date_embauche':'','salaire':25,'vitesse':5,'agilite':34,'deduction':2,'choisi':false},
{'identifiant':5,'prenom':'Gogok','nom':'Rodolphe','categorie':1,'ville':'Paris','age':17,'date_embauche':'','salaire':28,'photo':'3.jpg','vitesse':68,'agilite':75,'deduction':2,'choisi':false},
{'identifiant':6,'prenom':'Thierry','nom':'Chalamerto','categorie':1,'ville':'Paris','age':17,'date_embauche':'','salaire':28,'vitesse':55,'agilite':57,'deduction':75,'choisi':false},
{'identifiant':7,'prenom':'Gawivk','nom':'Gonzogues','categorie':2,'ville':'Paris','age':14,'date_embauche':'','salaire':25,'vitesse':10,'agilite':44,'deduction':2,'choisi':false},
{'identifiant':8,'prenom':'Thomas','nom':'Choubal','categorie':1,'ville':'Paris','age':12,'date_embauche':'','salaire':28,'vitesse':5,'agilite':3,'deduction':2,'choisi':false}
];
var iwanttofilter = [2,3,8];
$scope.cust = function(){
return function(item){
return iwanttofilter.find(k=> item.identifiant == k)
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="item in footballers | filter:cust() track by $index ">{{item.identifiant}} </div>
</div>
You pass the iwanttofilter into the filter, and filter your list based on each item.
MyApp.filter("fewerFootballers", [
function() {
return function(footballers, iwanttofilter) {
return arrayIntersection(footballers, iwanttofilter);
function arrayIntersection(a, b) {
return a.filter(function(x) {
return b.indexOf(x.identifiant) != -1;
});
}
}
}]);
In your html you use the filter.
{{ $scope.footballers | fewerFootballers: $scope.iwanttofilter }}

Angular filter match by character?

I have angular 1.3, and i have the following array:
data : [
{
id :2,
name : "danny davids",
age :9
},
{
id :3,
name : "sanny gordon",
age :9
}
]
I want the filter to do the follwing:
When i start writing the word "s", i want the danny davids to disappear, right now the default behavior is, both of them are still shown (the s is in the end of the last name of danny).
strict mode is something that i dont want to use, the behavior i want is:
if there is no value in the input, i want to see all, if i start to write i want to see the exact one by firstName/lastName.
is there a default filter for this in angular 1.3?
You can filter match by any characters:
Sample condition:
yourDataList.display.toLowerCase().indexOf(searchData) !== -1;
Example:
function createFilterForAnycharacters(searchData) {
var lowercaseQuery = query.toLowerCase();
return function filterFn(yourDataList) {
return (yourDataList.display.toLowerCase().indexOf(searchData) !== -1);
};
}
I suggest using $filter by a custom filter function for you ng-repeat. According to the documentation, $filter expects
function(value, index, array): A predicate function can be used to write arbitrary filters. The function is called for each element of the array, with the element, its index, and the entire array itself as arguments.
And only elements that return true with be shown. So all you have to do is write that function.
Your filter function might look like this:
$scope.filterData = function (obj) {
return anyNameStartsWith(obj.name, $scope.searchFilter);
};
function anyNameStartsWith (fullname, search) {
//validate if name is null or not a string if needed
if (search === '')
return true;
var delimeterRegex = /[ _-]+/;
//split the fullname into individual names
var names = fullname.split(delimeterRegex);
//do any of the names in the array start with the search string
return names.some(function(name) {
return name.toLowerCase().indexOf(search.toLowerCase()) === 0;
});
}
Your HTML might look something like this:
<input type="text" ng-model="searchFilter" />
<div ng-repeat="obj in data | filter : filterData">
Id: {{obj.id}}
Name: {{obj.name}}
</div>
A demo via plnkr
Use this custom filter to get result match starting characters
app.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.substr(0,letter.length).toLowerCase() == letter.toLowerCase()) {
filtered.push(item);
}
}
return filtered;
};
});
it works for your scenario, you can create custom filter
below is html code
<div ng-app="app">
<div ng-controller="PersonCtrl as person">
<input type="text" ng-model="letter" placeholder="Enter a letter to filter">
<ul>
<li ng-repeat="a in person.data | startsWithLetter:letter">
{{a.name}}
</li>
</ul>
</div>
</div>
js code
var app = angular.module('app', []);
app.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.name.substring(0, 1))) {
filtered.push(item);
}
}
return filtered;
};
});
app.controller('PersonCtrl', function () {
this.data = [
{
id :2,
name : "danny davids",
age :9
},
{
id :3,
name : "sanny gordon",
age :9
}
]
});
Need to create a custom filter function to do this. There is no default method to match first character in angular.
https://docs.angularjs.org/guide/filter

Filtering a nested ng-repeat: Hide parents that don't have children

I want to make some kind of project list from a JSON file. The data structure (year, month, project) looks like this:
[{
"name": "2013",
"months": [{
"name": "May 2013",
"projects": [{
"name": "2013-05-09 Project A"
}, {
"name": "2013-05-14 Project B"
}, { ... }]
}, { ... }]
}, { ... }]
I'm displaying all data using a nested ng-repeat and make it searchable by a filter bound to the query from an input box.
<input type="search" ng-model="query" placeholder="Suchen..." />
<div class="year" ng-repeat="year in data | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.months | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in month.projects | filter:query | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>
If I type "Project B" now, all the empty parent elements are still visible. How can I hide them? I tried some ng-show tricks, but the main problem seems so be, that I don't have access to any information about the parents filtered state.
Here is a fiddle to demonstrate my problem: http://jsfiddle.net/stekhn/y3ft0cwn/7/
You basically have to filter the months to only keep the ones having at least one filtered project, and you also have to filter the years to only keep those having at least one filtered month.
This can be easily achieved using the following code:
function MainCtrl($scope, $filter) {
$scope.query = '';
$scope.monthHasVisibleProject = function(month) {
return $filter('filter')(month.children, $scope.query).length > 0;
};
$scope.yearHasVisibleMonth = function(year) {
return $filter('filter')(year.children, $scope.monthHasVisibleProject).length > 0;
};
and in the view:
<div class="year" ng-repeat="year in data | filter:yearHasVisibleMonth | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.children | filter:monthHasVisibleProject | orderBy:sortMonth:true">
This is quite inefficient though, since to know if a year is accepted, you filter all its months, and for each month, you filter all its projects. So, unless the performance is good enough for your amount of data, you should probably apply the same principle but by persisting the accepted/rejected state of each object (project, then month, then year) every time the query is modified.
I think that the best way to go is to implement a custom function in order to update a custom Array with the filtered data whenever the query changes. Like this:
$scope.query = '';
$scope.filteredData= angular.copy($scope.data);
$scope.updateFilteredData = function(newVal){
var filtered = angular.copy($scope.data);
filtered = filtered.map(function(year){
year.children=year.children.map(function(month){
month.children = $filter('filter')(month.children,newVal);
return month;
});
return year;
});
$scope.filteredData = filtered.filter(function(year){
year.children= year.children.filter(function(month){
return month.children.length>0;
});
return year.children.length>0;
});
}
And then your view will look like this:
<input type="search" ng-model="query" ng-change="updateFilteredData(query)"
placeholder="Search..." />
<div class="year" ng-repeat="year in filteredData | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.children | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in month.children | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>
Example
Why not a custom $filter for this?
Efficiency: the nature of the $diggest cycle would make it much less efficient. The only problem is that this solution won't be as easy to re-use as a custom $filter would. However, that custom $filter wouldn't be very reusable either, since its logic would be very dependent on this concrete data structure.
IE8 Support
If you need this to work on IE8 you will have to either use jQuery to replace the filter and map functions or to ensure that those functions are defined, like this:
(BTW: if you need IE8 support there is absolutely nothing wrong with using jQuery for these kind of things.)
filter:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
'use strict';
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
map
if (!Array.prototype.map) {
Array.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
A = new Array(len);
k = 0;
while(k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[ k ];
mappedValue = callback.call(T, kValue, k, O);
A[ k ] = mappedValue;
}
k++;
}
return A;
};
}
Acknowledgement
I want to thank JB Nizet for his feedback.
For those who are interested: Yesterday I found another approach for solving this problem, which strikes me as rather inefficient. The functions gets called for every child again while typing the query. Not nearly as nice as Josep's solution.
function MainCtrl($scope) {
$scope.query = '';
$scope.searchString = function () {
return function (item) {
var string = JSON.stringify(item).toLowerCase();
var words = $scope.query.toLowerCase();
if (words) {
var filterBy = words.split(/\s+/);
if (!filterBy.length) {
return true;
}
} else {
return true;
}
return filterBy.every(function (word) {
var exists = string.indexOf(word);
if(exists !== -1){
return true;
}
});
};
};
};
And in the view:
<div class="year" ng-repeat="year in data | filter:searchString() | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.children | filter:searchString() | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in month.children | filter:searchString() | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>
Here is the fiddle: http://jsfiddle.net/stekhn/stv55sxg/1/
Doesn't this work? Using a filtered variable and checking the length of it..
<input type="search" ng-model="query" placeholder="Suchen..." />
<div class="year" ng-repeat="year in data | orderBy:'name':true" ng-show="filtered.length != 0">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.months | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in filtered = (month.projects | filter:query) | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>

Filter by multiple columns with ng-repeat

I'm wondering if there's an easy way in Angular to filter a table using ng-repeat on specific columns using or logic, rather than and. Right now, my filter is searching everything in the table (10+ columns of data), when it really only needs to filter on 2 columns of data (ID and Name).
I've managed to get it down to look only at those 2 columns when filtering (by using an object in the filter expression as per the docs and looking at this SO answer), but it's using and logic, which is too specific. I'd like to get it to use or logic, but am having trouble.
My HTML
<input type="text" ng-model="filterText" />
<table>
<tr ng-repeat="item in data"><td>{{ item.id }}</td><td>{{ item.name }}</td>...</tr>
</table>
My filter logic:
$filter('filter')(data, {id:$scope.filterText, name:$scope.filterText})
The filtering works, but again, it's taking the intersection of the matching columns rather than the union. Thanks!
It's not hard to create a custom filter which allows you to have as many arguments as you want. Below is an example of a filter with one and two arguments, but you can add as many as you need.
Example JS:
var app = angular.module('myApp',[]);
app.filter('myTableFilter', function(){
// Just add arguments to your HTML separated by :
// And add them as parameters here, for example:
// return function(dataArray, searchTerm, argumentTwo, argumentThree) {
return function(dataArray, searchTerm) {
// If no array is given, exit.
if (!dataArray) {
return;
}
// If no search term exists, return the array unfiltered.
else if (!searchTerm) {
return dataArray;
}
// Otherwise, continue.
else {
// Convert filter text to lower case.
var term = searchTerm.toLowerCase();
// Return the array and filter it by looking for any occurrences of the search term in each items id or name.
return dataArray.filter(function(item){
var termInId = item.id.toLowerCase().indexOf(term) > -1;
var termInName = item.name.toLowerCase().indexOf(term) > -1;
return termInId || termInName;
});
}
}
});
Then in your HTML:
<tr ng-repeat="item in data | myTableFilter:filterText">
Or if you want to use multiple arguments:
<tr ng-repeat="item in data | myTableFilter:filterText:argumentTwo:argumentThree">
Use this to search on All Columns (can be slow): search.$
AngularJS API: filter
Any Column Search:
<input ng-model="search.$">
<table>
<tr ng-repeat="friendObj in friends | filter:search:strict">
...
To expand on the excellent answer by #charlietfl, here's a custom filter that filters by one column(property) which is passed to the function dynamically instead of being hard-coded. This would allow you to use the filter in different tables.
var app=angular.module('myApp',[]);
app.filter('filterByProperty', function () {
/* array is first argument, each addiitonal argument is prefixed by a ":" in filter markup*/
return function (dataArray, searchTerm, propertyName) {
if (!dataArray) return;
/* when term is cleared, return full array*/
if (!searchTerm) {
return dataArray
} else {
/* otherwise filter the array */
var term = searchTerm.toLowerCase();
return dataArray.filter(function (item) {
return item[propertyName].toLowerCase().indexOf(term) > -1;
});
}
}
});
Now on the mark-up side
<input type="text" ng-model="filterText" />
<table>
<tr ng-repeat="item in data |filterByProperty:filterText:'name'"><td>{{ item.id }}</td><td>{{ item.name }}</td>...</tr>
</table>
I figured it out- I had to write my own custom filter. Here is my solution:
var filteredData;
filteredData = $filter('filter')(data, function(data) {
if ($scope.filter) {
return data.id.toString().indexOf($scope.filter) > -1 || data.name.toString().indexOf($scope.filter) > -1;
} else {
return true;
}
});
I created this filter to perform search in several fields:
var find = function () {
return function (items,array) {
var model = array.model;
var fields = array.fields;
var clearOnEmpty = array.clearOnEmpty || false;
var filtered = [];
var inFields = function(row,query) {
var finded = false;
for ( var i in fields ) {
var field = row[fields[i]];
if ( field != undefined ) {
finded = angular.lowercase(row[fields[i]]).indexOf(query || '') !== -1;
}
if ( finded ) break;
}
return finded;
};
if ( clearOnEmpty && model == "" ) return filtered;
for (var i in items) {
var row = items[i];
var query = angular.lowercase(model);
if (query.indexOf(" ") > 0) {
var query_array = query.split(" ");
var x;
for (x in query_array) {
query = query_array[x];
var search_result = true;
if ( !inFields(row,query) ) {
search_result = false;
break;
}
}
} else {
search_result = inFields(row,query);
}
if ( search_result ) {
filtered.push(row);
}
}
return filtered;
};
};
How to use:
<tr repeat="item in colletion
| find: {
model : model, // Input model
fields : [ // Array of fields to filter
'FIELD1',
'FIELD2',
'FIELD3'
],
clearOnEmpty: true // Clear rows on empty model (not obligatory)
} "></tr>
Easily We can do this type Following written code according you will easily create another field filter....
var myApp = angular.module('myApp',[]);
myApp.filter('myfilter',myfilter);
function myfilter(){
return function (items, filters) {
if (filters == null) {
return items;
}
var filtered = [];
//Apply filter
angular.forEach(items, function (item) {
if ((filters.Name == '' || angular.lowercase(item.Name).indexOf(angular.lowercase(filters.Name)) >= 0)
)
{
filtered.push(item);
}
});
return filtered;
};
}
myApp.controller('mycontroller',['$scope',function($scope){
$scope.filters={Name:'',MathsMarks:''};
$scope.students=[];
var i=0;
for(i=0;i<5;i++){
var item={Name:'',Marks:[]};
item.Name='student' + i;
item.Marks.push({Maths:50-i,Science:50 +i});
$scope.students.push(item);
}
}]);
<html ng-app='myApp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
</head>
<body ng-controller='mycontroller'>
<input type='text' name='studentName' ng-model="filters.Name" placeholder='Enter Student Name'>
<div ng-repeat="student in students | myfilter: filters">
Name : {{student.Name}} Marks == >
<span ng-repeat="m in student.Marks">Maths:{{m.Maths}} Science:{{m.Science}}</span>
</div>
</body>
</html>
Here is my solution, it's very lazy, it will search on all strings in array on first level, you could update this to recusively go down the tree, but this should be good enough...
app.filter('filterAll', function () {
return function (dataArray, searchTerm, propertyNames) {
if (!dataArray) return;
if (!searchTerm) {
return dataArray;
} else {
if (propertyNames == undefined) {
propertyNames = [];
for (var property in dataArray[0]) {
if(typeof dataArray[0][property] == "string" &&
property != "$$hashKey" &&
property != "UnitName" )
propertyNames.push(property);
}
}
console.log("propertyNames", propertyNames);
var term = searchTerm.toLowerCase();
return dataArray.filter(function (item) {
var found = false;
propertyNames.forEach(function(val) {
if (!found) {
if (item[val] != null && item[val].toLowerCase().indexOf(term) > -1)
found = true;
}
});
return found;
});
}
}
});
see this link Filter multiple object properties together in AngularJS

AngularJS Filter-- two filters with an 'or' relationship

Just wondering: in AngularJS, is there a native way to filter such that it has an 'or' relationship instead of the 'and' ?
for example:
<tr ng-repeat="account in accounts | filter1 *OR* filter2 *OR* filter3" >
so if any of the filters match, it returns that object. As of right now, all three have to pass in order for it to show up.
Thanks a lot,
Y
You could write a custom filter. It could accept the names of other filters and check each one of them to see if each item in the accounts array is a valid match against any of the filters. The following example shows kind of the idea, thought I haven't actually run the code to see if it works, so forgive me for any typos:
app.filter('anyOf', function($filter) {
return function(){
var array = arguments[0];
var result = [];
angular.forEach(array, function(item){
for(var i=1; i<arguments.length; i++){
var filter = $filter(arguments[i]);
if(filter([item]).length){
result.push(item);
break;
}
}
});
return result;
}
});
And then you would use it like so:
<tr ng-repeat="account in accounts | anyOf:'filter1':'filter2':'filter3'" >
I think it should work, though its not very efficient because its taking every item in the input array and checking it against any of the filters. But that might work if your accounts array wasn't super long.
You can use $filter to call filters in your own code, so you can pass the filter names as arguments to a new filter to merge the results (JSFIDDLE).
app.filter('merge', function($filter) {
return function(input, extra) {
var result = [];
for (var i = 1; i < arguments.length; i++) {
angular.forEach($filter(arguments[i])(input), function(item) {
if (result.indexOf(item) < 0) {
result.push(item);
}
});
}
return result;
};
});
And you can pass arguments to your filter like this:
<ul>
<li ng-repeat="item in items|merge:'color':'rating'">
{{item.rating}}: {{item.color}}
</li>
</ul>
If you wanted to pass arguments to the filter you're merging, you could parse them yourself in the merge filter:
<h3>Merge brown and rating >= 5</h3>
<ul>
<li ng-repeat="item in items|mergeWithArgs:['color','brown']:['rating',5]">
{{item.rating}}: {{item.color}}
</li>
</ul>
Code:
app.filter('mergeWithArgs', function($filter) {
return function(input) {
console.dir(arguments);
var result = [];
for (var i = 1; i < arguments.length; i++) {
var params = arguments[i];
var filter = $filter(params[0]);
// remove filter name, prepend input
params.splice(0, 1, input);
angular.forEach(filter.apply(this, params), function(item) {
if (result.indexOf(item) < 0) {
result.push(item);
}
});
}
return result;
};
});

Resources