custom interval filter in angularjs - angularjs

I have a collection which is ordered well until i use my custom filter on it. The filter does check if a value of each key in the collection is in a certain range.
Case 1: works fine.
ng-repeat="match in matches | orderBy: matchnumber"
Case 2: does not order! range check performs well.
ng-repeat="match in matches | orderBy: matchnumber | range:1:20"
ng-repeat="match in matches | range:1:20 | orderBy: matchnumber"
My filter:
myApp.filter('range', function() {
return function(matches, min, max) {
var result = {};
angular.forEach(matches, function(match, key) {
if (match.matchnumber >= min && match.matchnumber <= max) {
result[key] = match;
}
});
return result;
};
});

Related

Filtering based on search with Pagination i.e. on entire set of records

I am able to search only the current page records, However I need to search the entire set of records returned from server. This is my code:
<tr ng-repeat="brt in $parent.visibleBrtList = (currBrtList
| orderBy: state.orderBy : state.reverseOrderByDirection
| filter: pageFilter(state.page, state.itemsPerPage)
| filter: searchKeyword) ">
I have also tried to modify it like this:
<tr ng-repeat="brt in currBrtList
| filter: pageFilter(state.page, state.itemsPerPage)
| filter: searchKeyword">
currBrtList has 200 records, itemsPerPage is 10.
Here is pageFilter function:
$scope.pageFilter = function() {
var from = $scope.state.page * $scope.state.itemsPerPage;
var to = from + $scope.state.itemsPerPage;
return function(item, index) {
return index >= from && index < to;
}
}
Use the limitTo filter for pagination:
<tr ng-repeat="brt in currBrtList
| orderBy: state.orderBy : state.reverseOrderByDirection
| filter: searchKeyword
̶|̶ ̶f̶i̶l̶t̶e̶r̶:̶ ̶p̶a̶g̶e̶F̶i̶l̶t̶e̶r̶(̶s̶t̶a̶t̶e̶.̶p̶a̶g̶e̶,̶ ̶s̶t̶a̶t̶e̶.̶i̶t̶e̶m̶s̶P̶e̶r̶P̶a̶g̶e̶)̶
| limitTo: state.itemsPerPage : state.page*state.itemsPerPage" >
The first argument is the limit; the second, the begin.
Also be sure to filter before pagination.
For more information, see
AngularJS limitTo Filter API Reference

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>

count value in a array into ng-repeat

I have this data : http://www.monde-du-rat.fr/API/moulinette/radio/posts.json , from cakephp app, it's song by song, with attached votes
I use it as a service into a angularjs app, and i displayed it like this in html :
<div ng-repeat="song in songs | orderBy:'Radio.idSong' | notesong:'Radiovote'" class="list-group-item" id="{{song.Radio.idSong}}" ng-class="{ 'active' : songPlayed_name == song.Radio.name }" ng-if="songs">
<span>{{song.Radio.idSong}} - {{song.Radio.title}}</span><br />
<span>{{note}}%</span>
</div>
So, i want to count each attached vote, and define with values 'good' or 'bad', the % of likes
I try to made this filter :
/* notesong */
app.filter('notesong', function() {
return function(input) {
// counter init
var countGood = 0;
// if there is no votes, so note is zero
if (!angular.isArray(input)) {
var note = 0;
} else {
// loop for each vote (from Radiovote array, each value)
angular.forEach(input, function () {
if (input.value == 'good') {
countGood = countGood + 1;
}
});
var note = (countGood * input.length) / 100;
}
// final return
return note;
};
});
It's not working apparently (no errors, and no data displayed), so, what is the correct way ?
You are applying the filter in the wrong place. Instead of using it on the ng-repeat you should use it on the property you want to bind, like this:
<div ng-repeat="song in songs | orderBy:'Radio.idSong'" class="list-group-item" id="{{song.Radio.idSong}}" ng-class="{ 'active' : songPlayed_name == song.Radio.name }" ng-if="songs">
<span>{{song.Radio.idSong}} - {{song.Radio.title}}</span><br />
<span>{{song.Radiovote | notesong}}%</span>
</div>
There's also a problem with the way you are looping the votes in your filter. Update the following lines:
// loop for each vote (from Radiovote array, each value)
angular.forEach(input, function (item) {
if (item.value == 'good') {
countGood = countGood + 1;
}
});

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

angularjs - filter by multiple models

This seems like it must be simple, I just cannot find the answer.
Let's say I have an array of data, set out like the following:
friends = [{name:'John', age:60, location:'Brighton', street:'Middle Street'},
{name:'Bob', age:5, location:'Brighton', street:'High Street'}];
Now, I want to filter the data based on a text input like so:
<input ng-model="searchText">
<ul>
<li ng-repeat="friend in friends | orderBy:'name' | filter:searchText">
{{friend.name}} - {{friend.location}}</li>
</ul>
This works fine but it filters the input text based on every attribute of the friend object (name, age, location and street). I'd like to be able to filter based on name and location only (ignoring age and street). Is this possible without a custom filter?
Yes, it's possible by simply passing a predicate to the filter instead of a string:
<li ng-repeat="friend in friends | orderBy:'name' | filter:friendContainsSearchText">
$scope.friendContainsSearchText = function(friend) {
return friend.name.indexOf($scope.searchText) >= 0 || friend.location.indexOf($scope.searchText) >= 0
}
Here is how we do it with a custom filter.
DEMO: http://plnkr.co/edit/q7tYjOvFjQHSR0QyGETj?p=preview)
[array] | search:query:columns:operator
> query: this is the term you are looking for
> columns: an array of the names of the properties you want to look for (if empty, will use the angular filter with query)
> operator: a boolean to switch between OR (true) and AND (false, default)
html
<ul>
<li ng-repeat="item in list | search:query:['name','location']:operator">
<pre>{{item | json}}</pre>
</li>
</ul>
js
app.filter('search', function($filter) {
return function(input, term, fields, operator) {
if (!term) {
return input;
}
fields || (fields = []);
if (!fields.length) {
return $filter('filter')(input, term);
}
operator || (operator = false); // true=OR, false=AND
var filtered = [], valid;
angular.forEach(input, function(value, key) {
valid = !operator;
for(var i in fields) {
var index = value[fields[i]].toLowerCase().indexOf(term.toLowerCase());
// OR : found any? valid
if (operator && index >= 0) {
valid = true; break;
}
// AND: not found once? invalid
else if (!operator && index < 0) {
valid = false; break;
}
}
if (valid) {
this.push(value);
}
}, filtered);
return filtered;
};
});
Alternatively you can use:
<li ng-repeat="friend in friends | orderBy:'name' | filter:{ name :searchText}">
You can put several filters just like ....
<div>
<input ng-model="Ctrl.firstName" />
<input ng-model="Ctrl.age" />
<li ng-repeat = "employee in Ctrl.employees | filter:{name:Ctrl.firstName} | filter:{age:Ctrl.age}">{{employee.firstName}}</li>
</div>

Resources