Search code examples
javascriptangularjsasynchronouspromiseangularjs-filter

Use promise with angularjs user filter


I have a user filter. You can see the mock example below (it returns the same data which it gets, i.e. users_data_contents, in reality there is the function call):

var appModule = angular.module('appModule', [])
    .filter('filter_ghosts', function($rootScope){
        return function(users_data_contents){ // gets data from view
            return users_data_contents;
        };
    });

I need to use it in async mode, but not quite understand how. I tried something like this:

var appModule = angular.module('appModule', [])
    .filter('filter_ghosts', function($rootScope){    
        function getPromised(){
            var cnt = 0, intrv = setInterval(function() {
                ++cnt;
                if (cnt>10) {
                    return function(users_data_contents){
                        clearInterval(intrv);
                        return users_data_contents;
                    }
                }
                if (cnt > 50) {
                    clearInterval(intrv);
                }
            }, 100);
        }
        getPromised.$stateful = true;
        return getPromised;
    });

But this doesn't work. The html where the filter is applied looks like this:

<tr ng-repeat="user_data in usersList | filter_ghosts">
    ....

Can anybody help?

UPD

The most close solution to my issue is here: AngularJS : Asynchronously initialize filter However, it is turned out that the more appropriate approach is not to use filter at all but bind the repeater to array which is changed on corresponding procedures.


Solution

  • Create an empty array in the scope. Then bind your ng-repeat with filter to that array. Then just fill that array with the values when your async operation completes.