简体   繁体   中英

How do I get this filter to return a value from $http or $resource

In my html i have something like {{ i.userId | userName }} . Basically I am trying to convert it to a name. I am using a filter to do it but I having many problems with the async function to get the data.

                app.filter('userName', function($http) {
                     return function(value) {
                         if (!value) return '';

                         var user;
                         $http({
                             method: 'GET',
                             url: 'http://localhost:3000/api/Users?filter=                                                                                                      
                             {"where":{"id":' + value + '}}'
                         }).success(function(response) {
                             user = response;
                         });

                         return user.name;

                     }
                 });

I tried to put it in a callback format but I couldn't get it to work.

Using async call in filter will not work as Angular assumes your filters are side effect free and only executes them when the model changes. Before the async call returns the filter has done its work and will not get called in future till model updates.

Your options are to make the filter stateful by defining $stateful property on the filter function:

function filterFunction(value) {
    if (!value) return '';

    var user;
    $http({
        method: 'GET',
        url: 'http://localhost:3000/api/Users?filter=                                                                                                      
                                 {"where":{"id":' + value + '}}'
    }).success(function (response) {
        user = response;
    });

    return user.name;

}
filterFunction.$stateful = true;
return filterFunction;

When you make the filter stateful as above, Angular will evaluate this on each digest cycle. So this is not performant at all.

Please see the developer guide on filter

Better way will be to get the user list at one go and then search in this list by implementing a custom filter that takes this list as input too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM