My goal is to write an AngularJS ordering function, which behaves similarily, for example, to MySQL's "ORDER BY column1, column2". Means: if "column1" is same, sort by "column2".
The solution for only one criterium is, as known:
$scope.myOrderFn = function (item) {
return item.column1;
}
How to add the second criterium?
It seems to be that the sort function is more a "order by key extract function".
Therefore you cannot just concat string values because this would break the sorting.
However, you can pass more than one sort function as you would with column names. It's not in the offical documentation but the source is straightforward.
I think your only option is to pass two sort functions as you would with the sort columns:
Template
<div ng-repeat="item in items | orderBy:['column1','column2']">
{{item.column1}}-{{item.column2}}
</div>
<div ng-repeat="item in items | orderBy:[sort1,sort2]">
{{item.column1}}-{{item.column2}}
</div>
Controller
$scope.sort1 = function (item) {
return item.column1;
}
$scope.sort2 = function (item) {
return item.column2;
}
Related
I've been trying to make a list of geozones, with a select of taxes each (not all taxes apply to all geozones).
So I did a ng-repeat for the geozones, and inside each of them a ng-repeat with all taxes. Problem is I don't know how to send the id of the geozone being filtered at the moment. This is the code right now:
<md-option ng-repeat="tax in taxClasses | filter: filterTax" value="{{ '{{ tax.id }}' }}">{{ '{{ tax.name }}' }}</md-option>
and the JS:
$scope.filterTax = function(tax, n){
angular.forEach(tax.geoZone , function(geo){
if(geo === $scope.prices[n].geozoneId){
return true;
}
});
return false;
};
Need n to be the index of the geozone, or something of the sort. Thanks in advance!
Your idea is not that far off, but using filter: is not even necessary, as the pipe | is already a filter command:
ng-repeat="<var> in <array> | <filterFunction>:<...arguments>"
Thus you can create a filter (see https://docs.angularjs.org/guide/filter for details on that)
ng-repeat="tax in taxClasses | filterTax: <geozoneIndex>"
The value form the collection will be passed as the first argument of your filterTax function. Any further argument is passed separated by a colon :.
When you use this, you have to propagate a filter method like this:
app.module(...).filter('filterTax', function(/* injected services */) {
return function (/* arguments */ input, geozoneIndex) {
// function body
}
});
Alternatively use a filter function from your scope:
// template
ng-repeat="tax in filterTaxes(taxClasses, <geozoneIndex>)"
// script
$scope.filterTaxes = function(taxClasses, geozoneIndex) {
// do the whole filtering, but return an array of matches
return taxClasses.filter(function(taxClass) {
return /* in or out code */;
});
};
This means your geozoneIndex may be either a fixed value or being pulled from a variable, that's available in that scope.
Just be aware that your filterTax function will be called a lot, so if your page is getting slow you might want to consider optimizing that filtering.
I have following filter in angularJS:
<div ng-repeat="node in data | filter:{parentID:12}"></div>
This works fine (I get only data, where parentID is 12).
In the next step, I want to get all data, where parentID is (for example) 12,13,25 or 30.
I tried following (its not working):
filter:{parentID:[12,13,25,30]}
Is there any way to build a filter as described?
Thank you very much!
A predicate function will suit your needs nicely! From the doc:
function(value, index): A predicate function can be used to write arbitrary
filters. The function is called for each element of array. The final result
is an array of those elements that the predicate returned true for.
For example:
<div ng-repeat="node in data | filter:checkParentID"></div>
And in your controller
$scope.checkParentID = function(value, index) {
return value.parentID && [12,13,25,30].indexOf(value.parentID) !== -1;
}
I am using order by of Angular for sorting but I want to sort data based on three different fields, i.e success, in-progress and failed, without using any constant and variable directly from in-built function. Is there any way?
If you want you can call a function to sort your data as you want.
you can call following custom 'orderBy'
$scope.sort = function(column,reverse) {
$scope.persons = $filter('orderBy')($scope.persons,column,reverse);
};
'$scope.persons' - is your collection of data you need to order
'column' - name of the column you want to sort data
'reverse'- bool value to reverse the order
and you can call this 'sort' function from your View(HTML) as below.
data-ng-click="sort('name',nameReverse)"
you can pass array of fields to orderBy
<div ng-repeat="row in list | orderBy:['param1','param2']">
....
</div>
EDIT
to do it in javascript
$scope.sortedList = $filter('orderBy')(list,['param1', 'param2']);
EDIT
in smart table
function customSortAlgorithm(arrayRef, sortPredicate, reverse) {
//do some stuff
return sortedArray;
}
scope.globalConfig = {
sortAlgorithm: customSortAlgorithm
};
I'm using ng-repeat to create a list of entires and using a filter.
Is it possible to get the number of entries returned, like a length
data-ng-repeat="entry in entries | filter: { country_code : countryCode }"
It is little bit tricky, use ng-init:
ng-init="filter_len = (entries | filter: { country_code : countryCode }).length"
Example: http://jsfiddle.net/KJ3Nx/
As you know filter responsible to "filter" the input list and it returns filtered list where objects have the same structure. Otherwise you get digest cycle reentering that causes Exceptions (aka > 10 cycles).
1st way
Get length after filtering:
<pre>{{(entries| myfilter:types).length }}</pre>
See Example
2nd way
Use custom filter and get length from there.
iApp.filter('myfilter', function() {
return function( entries) {
var filtered = [];
angular.forEach(entries, function(entry) {
filtered.push(entry);
});
// here fetch list length
return filtered;
};
});
I suppose the following code will work for you:
<p>Filtered number: {{(entries|filter:{country_code:countryCode}).length}}</p>
<p>Total number: {{entries.length}}</p>
Inside my controller, I would like to filter an array of objects. Each of these objects is a map which can contain strings as well as lists
I tried using $filter('filter')(array, function) format but I do not know how to access the individual elements of the array inside my function. Here is a snippet to show what I want.
$filter('filter')(array, function() {
return criteriaMatch(item, criteria);
});
And then in the criteriaMatch(), I will check if each of the individual property matches
var criteriaMatch = function(item, criteria) {
// go thro each individual property in the item and criteria
// and check if they are equal
}
I have to do all these in the controller and compile a list of lists and set them in the scope. So I do need to access the $filter('filter') this way only. All the examples I found in the net so far have static criteria searches inside the function, they don't pass an criteria object and test against each item in the array.
You can use it like this:
http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
Like you found, filter accepts predicate function which accepts item
by item from the array.
So, you just have to create an predicate function based on the given criteria.
In this example, criteriaMatch is a function which returns a predicate
function which matches the given criteria.
template:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
scope:
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};
Here's an example of how you'd use filter within your AngularJS JavaScript (rather than in an HTML element).
In this example, we have an array of Country records, each containing a name and a 3-character ISO code.
We want to write a function which will search through this list for a record which matches a specific 3-character code.
Here's how we'd do it without using filter:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
for (var i = 0; i < $scope.CountryList.length; i++) {
if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
return $scope.CountryList[i];
};
};
return null;
};
Yup, nothing wrong with that.
But here's how the same function would look, using filter:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })
// If 'filter' didn't find any matching records, its result will be an array of 0 records.
if (matches.length == 0)
return null;
// Otherwise, it should've found just one matching record
return matches[0];
};
Much neater.
Remember that filter returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.
Hope this helps.
Additionally, if you want to use the filter in your controller the same way you do it here:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
You could do something like:
var filteredItems = $scope.$eval('items | filter:filter:criteriaMatch(criteria)');