Looking to implement a filter that, when clicked on a specific name, displays only that name:
{'username': 'julio', 'status': 'created'}, {'username': 'julio', 'status': 'running'}
Then, if a certain criteria is clicked, it should display just the object with that criteria:
{'username': 'julio', 'status': 'created'}
Check out the plunkr example: http://plnkr.co/edit/qDUvvBWQtNrLTLgSC8Yq?p=preview
angular.module('app', [])
.controller('Ctrl', function ($scope) {
$scope.users = [
{'username': 'julio', 'status': 'created'},
{'username': 'julio', 'status': 'running'},
{'username': 'phillip', 'status': 'running'},
{'username': 'mats', 'status': 'created'}
];
$scope.filtered = [];
$scope.optionProp = '';
$scope.includeItem = function(item, prop) {
$scope.optionProp = prop;
var idx = $scope.filtered.indexOf(item);
if (idx > -1) {
$scope.filtered.splice(idx, 1);
} else {
$scope.filtered.push(item);
}
}
$scope.filterFn = function(item) {
if ($scope.filtered.length > 0) {// first time
console.info( $scope.filtered.length > 0 );
if ($scope.filtered.indexOf(item[$scope.optionProp]) < 0){
console.warn( $scope.filtered.indexOf(item.username ) );
return;
}
}
return item;
}
})
.filter("unique", function () {
return function (data, propertyName) {
if (angular.isArray(data) && angular.isString(propertyName)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyName];
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
}
});
<body ng-controller="Ctrl">
<div ng-repeat="user in users | unique:'username'">
<input type="checkbox" ng-click="includeItem(user, 'username')" /> {{user}}
</div>
<hr />
<div ng-repeat="s in users | unique:'status'">
<input type="checkbox" ng-click="includeItem(s, 'status')"/> {{s}}
</div>
<ul>
<li ng-repeat="u in users | filter:filterFn">
<p>{{u.username}}</p>
<p>{{u.status}}</p>
</li>
</ul>
</body>