1

Not sure if this is possibly with Angular but it would be lovely it was.

Say I have a json object of cars. So lots of models and lots of makes (Ford, Vauxhall, Volkswagon, etc). I am then going to use a data-ng-repeat to list all the cars.

But I want to list of checkboxes to be able to filter by make of car. I won't know the possibly makes of cars until I get the JSON, so I can't pre-populate the list.

Here is a quick demo http://jsbin.com/AkiGaLO/3/edit

Now I could separately loop through all items, pull out the make, check if the make exists in another array, if not throw it in. But that all seems tiresome really :) and I could potentially be dealing with thousands of objects.

So is there a quick win in Angular? Or in normal JS for that matter.

Cheers

Leads
  • 839
  • 2
  • 10
  • 27
  • 1
    Not sure there's a particular angular directive especially for this. It's more about sorting and searching optimisation. If you wanted to be as efficient as possible with the population of the list of cars, you could sort the original list by make alphabetically then run through it. Add the first one to the list, then look at the next item. If it isn't the same as the previous item, add it to the list and move to the next item. If it is, just move onto the next item. – EvenStevens Sep 10 '13 at 14:16
  • 1
    There are several cool ways to do this here: http://stackoverflow.com/questions/1960473/unique-values-in-an-array . Personally I like the $.grep() answer. – Kokozaurus Sep 10 '13 at 14:18

1 Answers1

0

You can create a custom filter to return the unique list of names of the make of the car.

<div data-ng-repeat="carmake in cars | uniquemake">
    <input type="checkbox" ng-model="search[carmake]" />{{ carmake }}
</div>

app.filter('uniquemake', function () {
    return function (cars, length, end) {
        var result = {};
        angular.forEach(cars, function (car) {
            result[car.make] = 1;
        });
        return Object.keys(result);
    };
});
zs2020
  • 53,766
  • 29
  • 154
  • 219
  • Very sza and works a treat :) http://jsbin.com/AkiGaLO/6/edit (though haven't hooked up the searchnig yet but sure that'll be fine) – Leads Sep 10 '13 at 14:43