angularjs - Angular JS Custom Filter Trouble -
i'm working on learning angular js creating own app. focus angular, i'm not connecting database 1 in real world - have array of movies = [{title: '', genre: '', rating: ''}...]
hard coded js file.
i have series of buttons different movie ratings: g, pg, pg13, r. each button should work filter , return movies who's rating matches button. when button clicked, data.selectedrating
stores value. however, i'm running trouble built-in filter because if there no movies desired rating, return of them when should return none. , if "pg" button clicked returns movies rating of pg , pg13.
is there way fix this? thought may need make custom filter, i'm not sure how go (as i'm sure you'll able tell). suggestions? thanks!
here's have:
html
// data.selectedrating holds value of button clicked // built in filter looked this: // ng-repeat="movie in movies | filter: data.selectedrating" <table> <tr ng-repeat="movie in movies"> <td> {{movie.title | filterrating}} </td> </tr> </table>
js
angular.module('movieapp', ['nganimate', 'ui.router']) .factory('data', function() { return { sorttype: '', selectedgenre: '', selectedrating: ''}; }) .controller('formcontroller', ['$scope', 'data', function($scope, data) { $scope.data = data; $scope.movies = [ {title:'pitch perfect 2', genre: 'musical', rating: 'pg13'}, {title:'longest ride', genre: 'romance', rating: 'pg13'}, {title:'furious 7', genre: 'action', rating: 'pg13'}, {title:'home', genre: 'adventure', rating: 'pg'}, {title:'insurgent', genre: 'action', rating: 'pg13'} ]; }]) .filter('filterrating', function() { var out = []; return function(selectedrating, a) { if(selectedrating.rating == data.selectedrating) { out.push(selectedrating.title); } } return out; });
============================================
update - have added suggestions few of comments below - thanks! now, instead of name of movie, "undefined" return. ideas?
updated code: html:
... <td> {{movie.title | filterrating}} </td> ...
js
.filter('filterrating', function() { return function(selectedrating, movies) { var out = []; if(data.selectedrating == selectedrating.rating) { alert(' in here'); out.push(movies.title); } return out; } });
your code should :
html
<tr ng-repeat="movie in movies | filterrating "> <td> {{movie.title }} </td> </tr>
js
.filter('filterrating', function(data) { return function(selectedrating) { var out = []; (var = 0; < selectedrating.length; i++) { if(selectedrating[i].rating == data.selectedrating) { out.push(selectedrating[i]); } } return out; } });
the reason it, want filter movie object , not title itself
plunkr : http://plnkr.co/edit/nyax9kibhqyyxcqamyhc?p=preview
Comments
Post a Comment