Search code examples
jsonangularjsng-options

How to stop ng-option duplication repeat in Angularjs


Angular JS Select for filter

I have a create a search module which is able to search with input type text.. now i want to add select option in form to search filter it

Here is the Plunker : http://embed.plnkr.co/yPJADtUDcgU720dx8ChJ/preview


Solution

  • You can extract the categories from the json, then removing the duplication:

    //Filter all the categories, return an array of duplicated categories
    var allCategories = json.modules.map(function(item) {
      return item.category;
    });
    
    //Remove the duplication from the first array
    var filteredCategories = [];
    allCategories.forEach(function(item) {
      if (filteredCategories.indexOf(item) < 0) {
        filteredCategories.push(item);
      }
    });
    
    //Assign the filtered array to scope
    $scope.categories = filteredCategories;
    

    Change the html too:

    <select ng-model="search.category" ng-options="category for category in categories"></select>
    

    Working plunker: http://plnkr.co/edit/Z6IUMTzePO7UoWoGuUfP?p=preview