javascript - AngularJS Custom Filter with Argument -
my custom filter should output:
mark
...however it's outputting:
- m
- a
- r
- k
here's view:
<body ng-controller="mainctrl"> <ul> <li ng-repeat="friend in friends | myfriend:currentuser"> {{ friend }} </li> </ul> </body> ...and controller:
var app = angular.module('plunker', []); app.filter('myfriend', function () { return function (items, currentuser) { console.log(items); console.log(currentuser); (var = 0; < items.length; i++) { if (items[i] === currentuser) { return items[i]; } } }; }); app.controller('mainctrl', function($scope) { $scope.currentuser = 'mark'; $scope.friends = ['andrew', 'will', 'mark', 'alice', 'todd']; }); here plunker: http://plnkr.co/edit/jckat05mplrvizbcgo0n?p=preview
how can custom filter output "mark"?
as presume aware filter being applied list friends.
your filter returning single string value.
your ng-repeat can thought of as:
ng-repeat="friend in (friends | myfriend:currentuser)" which means trying loop on string returned myfriend filter. browser you're using ng-repeat on string loops on each character in string.
(note: might not happen on every browser, because browsers (e.g. ie7) do not allow [] subscripting on strings. (underneath all, ng-repeat rely on value having length property , [] subscripting.)
the following may produce result want (assuming ever want 1 name shown list)
<body ng-controller="mainctrl"> <ul> <li> {{ friends | myfriend:currentuser }} </li> </ul> </body>
Comments
Post a Comment