I'm trying to understand the concept of custom filter in AngularJS. Therefor I've made a simple table which I want to filter. I know I can do the filtering simple with the built-in Angular filter, but I made this for exercise purpose. I know the filter is not completed yet. It doesn't return anything. First I want to solve the following:
I'm having a problem with adding an object to an array. It should be simple with array.push(object). But in the 'for loop' the previous object is being replaced by the new one. I don't know why that is happening. To investigate this problem I've added a few console.log's to see (and hopefully understand) what is happening. But I cannot figure it out.
There's is also another behavior I cannot explain: the loop is running twice: it goes through the same array (vm.players) a second time. Does anyone has an explanation for this behavior?
This is my angularJS script:
var app = angular.module('main', ['angular.filter'])
.filter('filterIns', function() {
return function(input, ins) {
var out = [];
var obj = {};
for (var i = 0; i < input.length; i++) {
if (input[i].instrument == ins) {
obj.name = input[i].name;
obj.instrument = input[i].instrument;
console.log(obj);
out.push(obj);
console.log('inside IF ' + i);
console.log(out);
}
}
}
})
.controller('DemoCtrl', function() {
var vm = this;
vm.players = [
{
"name": "Mariko",
"instrument": "horn"
}, {
"name": "Kareem",
"instrument": "cello"
}, {
"name": "Lance",
"instrument": "horn"
}, {
"name": "Gail",
"instrument": "flute"
}, {
"name": "Armand",
"instrument": "cello"
}, {
"name": "Anika",
"instrument": "flute"
}, {
"name": "Mallory",
"instrument": "clarinet"
}, {
"name": "Odysseus",
"instrument": "clarinet"
}, {
"name": "Colt",
"instrument": "cello"
}, {
"name": "Kessie",
"instrument": "violin"
}, {
"name": "Iola",
"instrument": "horn"
}
];
});
And the html:
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script data-require="[email protected]" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="main">
<div ng-controller="DemoCtrl as demo">
<div>
<table border="0">
<tr>
<th>name</th>
<th>instrument</th>
</tr>
<tr ng-repeat="nr in demo.players | filterIns:'flute' ">
<td>{{nr.name }}</td>
<td>{{nr.instrument}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Please have a look at this plunk