Custom order using orderBy in ng-repeat - angularjs

I have objects like this:
students = {name: 'Aa_Student', class: 'A_Class'},
{name: 'Ab_Student', class: 'A_Class'},
{name: 'Ac_Student', class: 'B_Class'},
{name: 'Ba_Student', class: 'B_Class'},
{name: 'Bb_Student', class: 'C_Class'},
{name: 'Bc_Student', class: 'C_Class'}
Let's say the students object is shuffled. I use ng-repeat to show the data. I want to sort the objects in the custom order.
For example, I want to show the data like this:
Name Class
-----------------------------
Ac_Student B_Class
Ba_Student B_Class
Aa_Student A_Class
Ab_Student A_Class
Bb_Student C_Class
Bc_Student C_Class
So basically, I want to order by student's class, but it B_Class comes first, then A_Class, then C_Class. Also, I want to order by students name in alphabetic order. How can I do this?
HTML:
<table>
<tr ng-repeat="student in students | orderBy:customOrder">
...
</tr>
</table>
Controller:
$scope.customOrder = function(student) {
$scope.students = $filter('orderBy')(student, function() {
});
};

Hi you can create custom sort filter please see here http://jsbin.com/lizesuli/1/edit
html:
<p ng-repeat="s in students |customSorter:'class'">{{s.name}} - {{s.class}} </p>
</div>
angularjs filter:
app.filter('customSorter', function() {
function CustomOrder(item) {
switch(item) {
case 'A_Class':
return 2;
case 'B_Class':
return 1;
case 'C_Class':
return 3;
}
}
return function(items, field) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
return (CustomOrder(a.class) > CustomOrder(b.class) ? 1 : -1);
});
return filtered;
};
});

Know this is old but may come in handy for others...
You could also create a simple custom sort function. "Not quite a filter":
$scope.customOrder = function (item) {
switch (item) {
case 'A_Class':
return 2;
case 'B_Class':
return 1;
case 'C_Class':
return 3;
}
};
And then use like you wanted to:
<table>
<tr ng-repeat="student in students | orderBy:customOrder">
...
</tr>

to set the orderBy as a property of the objects just quote that property name within the markup:
ng-repeat="student in students |orderBy:'name' | orderBy:'class'"
DEMO

Related

How to bind two ng-models values together

I have a JSON file displayed as a table, I want to search inside this table using two steps:
Selecting an option from a select menu to choose in which column you want to search.
an input, for typing the keyword you want to search for.
So how can I concatenate the value of the "selected option form select tag" with the value of the "input"?
For example, the User selected the option "Names" from the select menu then he entered "John" inside the input
Here is my code:
https://jsfiddle.net/p1nkfpez/7/
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$scope.selection = "nm";
$http.get("https://api.myjson.com/bins/i9h1v")
.then(function(response) {
$scope.myRows = response.data;
$scope.rowsStatus = response.status;
$scope.rowsStatusText = response.statusText;
});
});
I want the Angular filter to be like:
filter:keyword.selection
You can create a function to create the filter object dynamicly:
$scope.getFilter = function() {
return {
[$scope.selection]: $scope.keyword
}
}
And use it like this:
<tr data-ng-repeat="row in myRows | filter:getFilter()">
...
</tr>
You can create a custom filter in which you can access your properties by name.
Custom filter
$scope.myCustomFilter = function(row){
if($scope.keyword == undefined || $scope.keyword.length == 0)
return true;
if(row[$scope.selection].toLowerCase().indexOf($scope.keyword) >= 0){
return true;
}
else
return false;
}
And add filter to your ng-repeat
<tbody>
<tr data-ng-repeat="row in myRows | filter: myCustomFilter">
<td>{{$index + 1}}</td>
<td>{{row.nm}}</td>
<td>{{row.cty}}</td>
<td>{{row.hse}}</td>
<td>{{row.yrs}}</td>
</tr>
</tbody>
Updated Fiddle

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 }}

angularjs filter ng-repeat links outside of list

Building a simple app that filters results based on an input field. I'm adding a bunch of links that are outside of the repeated list and when clicked I want to be able to filter the list below.
I've searched online for various ways of tackling this problem but have yet to find a solution.
I'm already filtering by search, however I'd like to be able to click a link that is a popular search entry.
My code is:
tag one
tag two
tag three
<tr ng-repeat="item in items | orderBy:'date' | filter:itemsFilter" ng-click="clickedItem(item.id)">
<td><img ng-src="{{item.imageUrl}}" alt="{{item.title}}"></td>
<td>
{{item.title}}<br>
</td>
<td><i class="el el-time"></i> {d{item.date}}</td>
<td class="drop-me">{{item.description}}</td>
<td class="tag-me">{{item.tag}}</td>
</tr>
<tr ng-hide="item.length == 0"><td><p>There are no items!</p></td></tr>
I've tried custom filters, just can't figure a way to inject the items via an ng-click and update the list below.
I'd like to click one of the tag links and it filter the list below
Thanks
As proposed in the comments you can create an array to which you're adding your tags for filtering and in a custom filter you can filter your items array.
Also ngTagsInput is a nice directive that's helping to create a input field with tags.
Please have a look at the demo below or this jsfiddle.
angular.module('demoApp', ['ngTagsInput'])
// filter from here (with some modifications) http://stackoverflow.com/questions/23785592/apply-dynamic-filters-using-tags
.filter('filterByTags', function() {
return function(items, tags) {
var filtered = []; // Put here only items that match
(items || []).forEach(function(item) { // Check each item
var matches = tags.some(function(tag) { // If there is some tag
return item.tag == tag.text;
}); // we have a match
if (matches) { // If it matches
filtered.push(item); // put it into the `filtered` array
}
});
return filtered.length == 0 ? items : filtered; // Return the array with items that match any tag // return all if no tags
};
})
.controller('mainController', MainCtrl);
function MainCtrl() {
var vm = this;
function isTagInTags(tag) {
var seen = false;
//console.log('test', tag);
for (var i = 0; i < vm.tags.length; i++) {
//console.log(vm.tags[i].text, tag);
if (vm.tags[i].text == tag) {
seen = true;
return seen;
}
}
return seen;
}
vm.addTag = function(tag) {
//console.log(tag);
if (!isTagInTags(tag)) {
vm.tags.push({
text: tag
});
}
};
vm.data = [{
id: 0,
tag: 'JavaScript',
title: 'this is JS related'
}, {
id: 1,
tag: 'Java',
title: 'this is Java related'
}, {
id: 2,
tag: 'Python',
title: 'this is Python related'
}, {
id: 3,
tag: 'Python',
title: 'also Python stuff...'
}];
var unique = [];
vm.availTags = [];
for (i in vm.data) {
var item = vm.data[i];
//console.log(item);
if (unique.indexOf(item.tag) === -1) {
unique.push(item.tag);
vm.availTags.push(item.tag);
}
}
vm.loadItems = function(query) {
//console.log(query);
return vm.availTags.filter(function(tag) {
var testTag = tag.toLowerCase();
return testTag.indexOf(query.toLowerCase()) >= 0;
});
//return $http.get('/tags?query=' + query); // use this with a backend
}
//console.log(vm.availTags);
vm.tags = []; //vm.availTags[0];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-tags-input/3.1.1/ng-tags-input.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/ng-tags-input/3.1.1/ng-tags-input.css" rel="stylesheet" />
<div ng-app="demoApp" ng-controller="mainController as ctrl">
<button ng-click="ctrl.addTag('JavaScript')">
JavaScript
</button>
<button ng-click="ctrl.addTag('Java')">
Java
</button>
<!--{{ctrl.tags}}-->
<tags-input ng-model="ctrl.tags">
<auto-complete source="ctrl.loadItems($query)"></auto-complete>
</tags-input>
<div ng-repeat="item in ctrl.data | filterByTags: ctrl.tags">
{{item.title}}
</div>
</div>
try addition ng-href
<a ng-href="">tag one</a>
<a ng-href="">tag two</a>
<a ng-href="">tag three</a>
<tr ng-repeat="item in items | orderBy:'date' | filter:itemsFilter" ng-click="clickedItem(item.id)">
<td><a ng-href="{{item.url}}"><img ng-src="{{item.imageUrl}}" alt="{{item.title}}"></a></td>
<td>
<a ng-href="{{item.url}}">{{item.title}}</a><br>
</td>
<td><i class="el el-time"></i> {d{item.date}}</td>
<td class="drop-me">{{item.description}}</td>
<td class="tag-me">{{item.tag}}</td>
</tr>
<tr ng-hide="item.length == 0"><td><p>There are no items!</p></td></tr>

$filter with OR [duplicate]

I want to use the filter in angular and want to filter for multiple values, if it has either one of the values then it should be displayed.
I have for example this structure:
An object movie which has the property genres and I want to filter for Action and Comedy.
I know I can do filter:({genres: 'Action'} || {genres: 'Comedy'}), but what to do if I want to filter it dynamically. E.g. filter: variableX
How do I set variableX in the $scope, when I have an array of the genres I have to filter?
I could construct it as a string and then do an eval() but I don't want to use eval()...
I would just create a custom filter. They are not that hard.
angular.module('myFilters', []).
filter('bygenre', function() {
return function(movies,genres) {
var out = [];
// Filter logic here, adding matches to the out var.
return out;
}
});
template:
<h1>Movies</h1>
<div ng-init="movies = [
{title:'Man on the Moon', genre:'action'},
{title:'Meet the Robinsons', genre:'family'},
{title:'Sphere', genre:'action'}
];" />
<input type="checkbox" ng-model="genrefilters.action" />Action
<br />
<input type="checkbox" ng-model="genrefilters.family" />Family
<br />{{genrefilters.action}}::{{genrefilters.family}}
<ul>
<li ng-repeat="movie in movies | bygenre:genrefilters">{{movie.title}}: {{movie.genre}}</li>
</ul>
Edit here is the link: Creating Angular Filters
UPDATE: Here is a fiddle that has an exact demo of my suggestion.
You can use a controller function to filter.
function MoviesCtrl($scope) {
$scope.movies = [{name:'Shrek', genre:'Comedy'},
{name:'Die Hard', genre:'Action'},
{name:'The Godfather', genre:'Drama'}];
$scope.selectedGenres = ['Action','Drama'];
$scope.filterByGenres = function(movie) {
return ($scope.selectedGenres.indexOf(movie.genre) !== -1);
};
}
HTML:
<div ng-controller="MoviesCtrl">
<ul>
<li ng-repeat="movie in movies | filter:filterByGenres">
{{ movie.name }} {{ movie.genre }}
</li>
</ul>
</div>
Creating a custom filter might be overkill here, you can just pass in a custom comparator, if you have the multiples values like:
$scope.selectedGenres = "Action, Drama";
$scope.containsComparator = function(expected, actual){
return actual.indexOf(expected) > -1;
};
then in the filter:
filter:{name:selectedGenres}:containsComparator
Here is the implementation of custom filter, which will filter the data using array of values.It will support multiple key object with both array and single value of keys. As mentioned inangularJS API AngularJS filter Doc supports multiple key filter with single value, but below custom filter will support same feature as angularJS and also supports array of values and combination of both array and single value of keys.Please find the code snippet below,
myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
var filterObj = {
data:items,
filteredData:[],
applyFilter : function(obj,key){
var fData = [];
if (this.filteredData.length == 0)
this.filteredData = this.data;
if (obj){
var fObj = {};
if (!angular.isArray(obj)){
fObj[key] = obj;
fData = fData.concat($filter('filter')(this.filteredData,fObj));
} else if (angular.isArray(obj)){
if (obj.length > 0){
for (var i=0;i<obj.length;i++){
if (angular.isDefined(obj[i])){
fObj[key] = obj[i];
fData = fData.concat($filter('filter')(this.filteredData,fObj));
}
}
}
}
if (fData.length > 0){
this.filteredData = fData;
}
}
}
};
if (keyObj){
angular.forEach(keyObj,function(obj,key){
filterObj.applyFilter(obj,key);
});
}
return filterObj.filteredData;
}
}]);
Usage:
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}
Here is a fiddle example with implementation of above "filterMutiple" custom filter.
:::Fiddle Example:::
If you want to filter on Array of Objects then you can give
filter:({genres: 'Action', key :value }.
Individual property will be filtered by particular filter given for that property.
But if you wanted to something like filter by individual Property and filter globally for all properties then you can do something like this.
<tr ng-repeat="supp in $data | filter : filterObject | filter : search">
Where "filterObject" is an object for searching an individual property and "Search" will search in every property globally.
~Atul
I've spent some time on it and thanks to #chrismarx, I saw that angular's default filterFilter allows you to pass your own comparator. Here's the edited comparator for multiple values:
function hasCustomToString(obj) {
return angular.isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
}
var comparator = function (actual, expected) {
if (angular.isUndefined(actual)) {
// No substring matching against `undefined`
return false;
}
if ((actual === null) || (expected === null)) {
// No substring matching against `null`; only match against `null`
return actual === expected;
}
// I edited this to check if not array
if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
// Should not compare primitives against objects, unless they have custom `toString` method
return false;
}
// This is where magic happens
actual = angular.lowercase('' + actual);
if (angular.isArray(expected)) {
var match = false;
expected.forEach(function (e) {
e = angular.lowercase('' + e);
if (actual.indexOf(e) !== -1) {
match = true;
}
});
return match;
} else {
expected = angular.lowercase('' + expected);
return actual.indexOf(expected) !== -1;
}
};
And if we want to make a custom filter for DRY:
angular.module('myApp')
.filter('filterWithOr', function ($filter) {
var comparator = function (actual, expected) {
if (angular.isUndefined(actual)) {
// No substring matching against `undefined`
return false;
}
if ((actual === null) || (expected === null)) {
// No substring matching against `null`; only match against `null`
return actual === expected;
}
if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
// Should not compare primitives against objects, unless they have custom `toString` method
return false;
}
console.log('ACTUAL EXPECTED')
console.log(actual)
console.log(expected)
actual = angular.lowercase('' + actual);
if (angular.isArray(expected)) {
var match = false;
expected.forEach(function (e) {
console.log('forEach')
console.log(e)
e = angular.lowercase('' + e);
if (actual.indexOf(e) !== -1) {
match = true;
}
});
return match;
} else {
expected = angular.lowercase('' + expected);
return actual.indexOf(expected) !== -1;
}
};
return function (array, expression) {
return $filter('filter')(array, expression, comparator);
};
});
And then we can use it anywhere we want:
$scope.list=[
{name:'Jack Bauer'},
{name:'Chuck Norris'},
{name:'Superman'},
{name:'Batman'},
{name:'Spiderman'},
{name:'Hulk'}
];
<ul>
<li ng-repeat="item in list | filterWithOr:{name:['Jack','Chuck']}">
{{item.name}}
</li>
</ul>
Finally here's a plunkr.
Note: Expected array should only contain simple objects like String, Number etc.
you can use searchField filter of angular.filter
JS:
$scope.users = [
{ first_name: 'Sharon', last_name: 'Melendez' },
{ first_name: 'Edmundo', last_name: 'Hepler' },
{ first_name: 'Marsha', last_name: 'Letourneau' }
];
HTML:
<input ng-model="search" placeholder="search by full name"/>
<th ng-repeat="user in users | searchField: 'first_name': 'last_name' | filter: search">
{{ user.first_name }} {{ user.last_name }}
</th>
<!-- so now you can search by full name -->
You can also use ngIf if the situation permits:
<div ng-repeat="p in [
{ name: 'Justin' },
{ name: 'Jimi' },
{ name: 'Bob' }
]" ng-if="['Jimi', 'Bob'].indexOf(e.name) > -1">
{{ p.name }} is cool
</div>
The quickest solution that I've found is to use the filterBy filter from angular-filter, for example:
<input type="text" placeholder="Search by name or genre" ng-model="ctrl.search"/>
<ul>
<li ng-repeat="movie in ctrl.movies | filterBy: ['name', 'genre']: ctrl.search">
{{movie.name}} ({{movie.genre}}) - {{movie.rating}}
</li>
</ul>
The upside is that angular-filter is a fairly popular library (~2.6k stars on GitHub) which is still actively developed and maintained, so it should be fine to add it to your project as a dependency.
I believe this is what you're looking for:
<div>{{ (collection | fitler1:args) + (collection | filter2:args) }}</div>
Please try this
var m = angular.module('yourModuleName');
m.filter('advancefilter', ['$filter', function($filter){
return function(data, text){
var textArr = text.split(' ');
angular.forEach(textArr, function(test){
if(test){
data = $filter('filter')(data, test);
}
});
return data;
}
}]);
Lets assume you have two array, one for movie and one for genre
Just use the filter as: filter:{genres: genres.type}
Here genres being the array and type has value for genre
I wrote this for strings AND functionality (I know it's not the question but I searched for it and got here), maybe it can be expanded.
String.prototype.contains = function(str) {
return this.indexOf(str) != -1;
};
String.prototype.containsAll = function(strArray) {
for (var i = 0; i < strArray.length; i++) {
if (!this.contains(strArray[i])) {
return false;
}
}
return true;
}
app.filter('filterMultiple', function() {
return function(items, filterDict) {
return items.filter(function(item) {
for (filterKey in filterDict) {
if (filterDict[filterKey] instanceof Array) {
if (!item[filterKey].containsAll(filterDict[filterKey])) {
return false;
}
} else {
if (!item[filterKey].contains(filterDict[filterKey])) {
return false;
}
}
}
return true;
});
};
});
Usage:
<li ng-repeat="x in array | filterMultiple:{key1: value1, key2:[value21, value22]}">{{x.name}}</li>
Angular Or Filter Module
$filter('orFilter')([{..}, {..} ...], {arg1, arg2, ...}, false)
here is the link: https://github.com/webyonet/angular-or-filter
I had similar situation. Writing custom filter worked for me. Hope this helps!
JS:
App.filter('searchMovies', function() {
return function (items, letter) {
var resulsts = [];
var itemMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if ( itemMatch.test(item.name) || itemMatch.test(item.genre)) {
results.push(item);
}
}
return results;
};
});
HTML:
<div ng-controller="MoviesCtrl">
<ul>
<li ng-repeat="movie in movies | searchMovies:filterByGenres">
{{ movie.name }} {{ movie.genre }}
</li>
</ul>
</div>
Here is my example how create filter and directive for table jsfiddle
directive get list (datas) and create table with filters
<div ng-app="autoDrops" ng-controller="HomeController">
<div class="row">
<div class="col-md-12">
<h1>{{title}}</h1>
<ng-Multiselect array-List="datas"></ng-Multiselect>
</div>
</div>
</div>
my pleasure if i help you
Too late to join the party but may be it can help someone:
We can do it in two step, first filter by first property and then concatenate by second filter:
$scope.filterd = $filter('filter')($scope.empList, { dept: "account" });
$scope.filterd = $scope.filterd.concat($filter('filter')($scope.empList, { dept: "sales" }));
See the working fiddle with multiple property filter
OPTION 1:
Using Angular providered filter comparator parameter
// declaring a comparator method
$scope.filterBy = function(actual, expected) {
return _.contains(expected, actual); // uses underscore library contains method
};
var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')(employees, {name: ['a','c']}, $scope.filterBy);
OPTION 2:
Using Angular providered filter negation
var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')($filter('filter')(employees, {name: '!d'}), {name: '!b'});
My solution
ng-repeat="movie in movies | filter: {'Action'} + filter: {'Comedy}"
the best answer is :
filter:({genres: 'Action', genres: 'Comedy'}

Equal Arrays AngularJS Pro

I need to show object only if one of it's properties equals to array.
I have a controller in app.js:
app.controller('checkBoxController', function ($scope) {
$scope.ingredients= [
{label: 'Egg', value: 1},
{label: 'Milk', value: 2},
$scope.selection=[];
$scope.toggleSelection = function toggleSelection(ingredientLabel) {
var idx = $scope.selection.indexOf(ingredientLabel);
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
else {
$scope.selection.push(ingredientLabel);
}
};
});
and an html code for it:
<span style="color:black;" class="selected-item">Selected Items:<span>
<div ng-repeat="label in selection" class="selected-item">
</div>
<div class="list-group">
<div class="list-group-item" ng-repeat="product in meals.products" ng-show="product.contents==selection">
<h1>{{product.name}}</h1>
<meal-gallery></meal-gallery>
<meal-tabs></meal-tabs>
</div>
</div>
And I Have { name: 'Scrambled Egg', contents: "Egg"} in array of products. So I need to show product if it's contents equals to selected ingredients.
I do not have problems when it is only one ingredient like "Egg", but if I need contents of two equal to selected?
It would be best to use a custom filter.
If you add lodash to your application, you can create a filter that will preform a following operation:
angular.module('common', [])
.filter('canBeMadeFrom', function() {
return function(product, ingredients) {
return _.intersection(product.contents, ingredients).length == product.contents.length';
};
});
this will return true if all of products contents are contained in ingredients
use it like this
ng-repeat='product in products | canBeMadeFrom:ingredients'
Use a filter.
<div ng-repeat=product in products |filter: product.a === a && product.b === b>
You can also use a function for filter. It's a function that takes in an item and returns Boolean

Resources