Here are my custom filters:
This filter removes records with the same property:
.filter('distinct', function () { //filter, which removes records with same property
retu function (data, keyname) {
var output = [],
keys = [];
angular.forEach(data, function (item) {
var key = item[keyname];
if (keys.indexOf(key) === -1) { //If not already existing
keys.push(key);
output.push(item);
}
});
retu output;
}
})
<select ng-model="search.level.level">
<option value="">All Levels</option>
<option ng-repeat="class in classes | distinct:'level'" value="{{class.level}}">{{class.level}}</option>
</select>
This filter replaces ids from an objects with a corresponding value from another array. (I am trying to do something like an 'Equijoin' from SQL in AngularJS. If there is a better way let me know :) )
.filter('replaceId', function () { //filter, which replaces Id's of one array, with corresponding content of another array
retu function (t_D, s_D, t_prop, s_prop) { //data of target, data of source, target property, source property
var replacment = {};
var output = [];
angular.forEach(s_D, function (item) {
replacment[item.id] = item[s_prop]; //replacment - object is filled with 'id' as key and corresponding value
});
angular.forEach(t_D, function (item) {
item[t_prop] = replacment[item[t_prop]]; //ids of target data are replaced with matching value
output.push(item);
});
retu output;
}
});
<tbody>
<tr ng-repeat="class in classes | filter:search.teacher | filter:search.level | filter:search.classNR | replaceId:teachers:'classTeacher':'prename' | orderBy:sortType:sortReverse">
<td>{{class.level}}</td>
<td>{{class.classNR}}</td>
<td>{{class.classTeacher}}</td>
<td><a href="#" ng-click="edit.show(class)"><i class="material-icons">edit</i></a>
</td>
<td><a href="#" ng-click="delete(class)"><i class="material-icons">delete</i></a>
</td>
</tr>
</tbody>
The first filter gets an Array (with objects) from the $scope and it retus a modified object, which is properly displayed. The second filter also gets an Array (with objects) from the $scope and also retus a modified object. The first time the filter is done (only observable with debugger), the data is properly displayed. But the array in the $scope is now overwritten with the modified data from the filter. I just wanted to change the displayed data, not the data in the $scope. I observed that the handed over array (of objects) of the second filter does contain $$hashedKeys, but the array of the first filter doesn't. Removing the hashed keys before retuing the output results in crashing AngularJs.
I thought filter only modify displayed data and dont overwrite the $scope. And what is the reason for the different behaviour of the first and the second filter in this regard?
