angularjs - Custom Filter not firing in angular1 -


i have 2 fields in digest: genres , secondary_genre integers.

i have dropdown fields of genres returns value (ng-model = query.genres)

i have tried create custom function compare genre , secondary genre query.genre , return if either condition met. individually work fine i.e filter:{secondary_genre:query.genre) or condition need custom.

the custom filter have written called with

<li ng-repeat="film in listoftitles | customgenrefilter:query.genre"> 

the filter is

.filter('customgenrefilter', function() {     return function(data, query) {         if (data) {             return data.filter(data.genres == query || data.secondary_genre == query);         }         else {             return [];         }     }; }); 

but throwing errors. how can write custom filter return item if condition genres = query.genre or secondary_genre = query.genre.

share|improve question
    
what query.genre object like? have query.genre.genres? – jarek kulikowski jul 28 @ 15:10
    
integer only, no strings or fancy crap.. whole number 1 x – moledesign jul 28 @ 18:02
up vote 1 down vote accepted

your filter not working because not using .filter() method properly, method require argument lambda function in return whether item should or not stay in list. in order fix code have change following line:

return data.filter(data.genres == query || data.secondary_genre == query); 

to:

return data.filter(function(item) {     return item.genre == query || item.secondary_genre == query }); 

the following example implements working version of filter.

angular.module('myapp', [])    .component('app', {      templateurl: '/app.html',      controller: app    })    .filter('customgenrefilter', customgenrefilter);    function app($scope) {    $scope.query = {      genre: ''    };    $scope.listoftitles = [      { title: 'test 1', genre: 'genre1' },      { title: 'test 2', genre: 'genre2' },    ];  }    function customgenrefilter() {    return function(data, query) {      if (query === '') return data;      if (data) return data.filter(function(item) {        return item.genre == query || item.secondary_genre == query      });      return [];    };  }    angular.element(function() {    angular.bootstrap(document, ['myapp']);  });
<script id="/app.html" type="text/ng-template">    <select ng-model="query.genre" ng-options="item item item in ['', 'genre1', 'genre2']">    </select>    <ul>      <li ng-repeat="film in listoftitles | customgenrefilter:query.genre">        {{ film.title }}      </li>    </ul>  </script>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>  <app />

share|improve answer
    
some minor tweaking needed fit in code, solution 10/10, brilliant, thanks. – moledesign jul 28 @ 18:27

your answer

 
discard

posting answer, agree privacy policy , terms of service.

not answer you're looking for? browse other questions tagged or ask own question.

Comments