I'm trying to use Angular filter to display only sorted tags by category
Example of a tag object
in tags array
:
{
term: term,
id: id,
category: category
}
The ng-repeat tags:
<li ng-repeat="(k, m) in tags | filter: filterTags | orderBy:predicate:reverse"
ng-class="{'selected': m.selected}"
ng-click="selectTag(m)">
<div class="tag">{{m.term}}</div>
</li>
The sort by category radio buttons:
<div class="category-selection">
<ul>
<li>
<input type="radio" ng-model="catSort" name="brand" value="brand">
Brand
</li>
<li>
<input type="radio" ng-model="catSort" name="client" value="client">
Client
</li>
In the sort radio button directive controller:
// Detect category sort
// Then apply the value to the filter function:
$scope.$watch('catSort', function(value) {
console.log(value);
tagsPanel = ScopeFactory.getScope('tagsPanel');
tagsPanel.filterTags(value);
});
I found out that filter is has it's own Angular module, so my question is, how do I get the category strings into this filter?
.filter('filterTags', function() {
return function(tags, category) {
return tags;
};
});
Here is where I capture the new category, how would I send the value into the filter above?
$scope.$watch('catSort', function(value) {
console.log(value);
});
If I got it right. You want to filter your tag object array by category.
You can call a scope method and return true if it matches the currently selected category. The parameter for this method will be a tag
object of your ng-repeat. So you can do a check like return tag.category == $scope.catSort;
Please have a look at the demo below and here at jsFiddle .
(I've took sport categories just to have some dummy data.)
angular.module('myApp', []) .controller('mainCtrl', function ($scope) { $scope.catSort = "football"; $scope.tags = [{ term: 'foot1', id: 'id', category: 'football' }, { term: 'foot2', id: 'id2', category: 'football' }, { term: 'base1', id: 'id', category: 'baseball' }, { term: 'base2', id: 'id2', category: 'baseball' }, ]; $scope.filterTags = function (tag) { //console.log(tag, $scope.catSort); return tag.category == $scope.catSort; }; });
ul { list-style-type: none; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="mainCtrl">Filter by category: <div class="category-selection"> <ul> <li> <input type="radio" ng-model="catSort" name="football" value="football" />Football</li> <li> <input type="radio" ng-model="catSort" name="baseball" value="baseball" />Baseball</li> </ul> </div>Teams: <ul> <li ng-repeat="(index, tag) in tags | filter: filterTags" ng-class="{'selected': tag.selected}" ng-click="selectTag(tag)"> <div class="tag">{{tag.term}}</div> </li> </ul> </div>
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.