I need to filter an array by using nested objects, it means filter the array by using multiple check boxes but I have an issue with the duplicate names. This is the source code I've been trying to use.
Any idea about how to fix the duplicate names issue?
html
<div data-ng-app="myApp">
<div data-ng-controller="controller">
<strong>Pick a brand to see the models</strong>
<div ng-init="group = (cars | groupBy:'make')">
<div ng-repeat="m in group">
<b><input type="checkbox" checked="true" ng-model="useMakes[$index]"/>{{m.name}}</b>
</div>
</div>
<br/>
<table border="1">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Maker</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="car in cars | filter:filterMakes()">
<td>{{$index+1}}</td>
<td>{{car.make.name}}</td>
<td>{{car.model}}</td>
</tr>
</tbody>
js
var myApp = angular.module('myApp',[]);
myApp.controller("controller", function($scope){
$scope.useMakes = [];
$scope.filterMakes = function () {
return function (p) {
for (var i in $scope.useMakes) {
if (p.make == $scope.group[i] && $scope.useMakes[i]) {
return true;
}
}
};
};
$scope.makes = [
{id:1, name: "BMV"},
{id:2, name: "Ford"},
{id:3, name: "Renault"},
{id:4, name: "Seat"},
{id:5, name: "Opel"}
];
$scope.cars = [
{model: '316', make: {id: 1, name: "BMV"}},
{model: '520', make: {id: 1, name: "BMV"}},
{model: 'Fiesta', make: {id: 2, name: "Ford"}},
{model: 'Focus', make: {id: 2, name: "Ford"}},
{model: 'Clio', make: {id: 3, name: "Renault"}},
{model: 'Toledo', make: {id: 4, name: "Seat"}},
{model: 'Leon', make: {id: 4, name: "Seat"}},
{model: 'Insignia', make: {id: 5, name: "Opel"}},
{model: 'Astra', make: {id: 5, name: "Opel"}},
{model: 'Corsa', make: {id: 5, name: "Opel"}}
];
});
/*I think here is the problem*/
var uniqueItems = function (data, key) {
var result = new Array();
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
if (result.indexOf(value) == -1) {
result.push(value);
}
}
return result;
};
myApp.filter('groupBy', function () {
return function (collection, key) {
if (collection === null) return;
return uniqueItems(collection, key);
};
});