Search code examples
javascriptangularjsangular-filters

How to show a loading message before filter with AngularJS?


I need to show some "Loading Message" when a filter is about to happen with AngularJS. My filter is fast, so I can't just show it before return the filtered data. My code:

.filter('filterName', function () {
    return function (pacotes, escopo) {
        var filtered = [];
        pacotes.forEach(function (pacote) {
            if (condition)
                filtered.push(pacote);
        });

        return filtered;
    }
})

What can I do to show some message, div, anything, before return this data?


Solution

  • Somewhere in your html:

    <p id="loadingMessage" ng-show="showMessage"></p>
    

    Filter:

    .filter('filterName', function () {
        $scope.showMessage = true;
    
        $timeout(return function (pacotes, escopo) {
            var filtered = [];
            pacotes.forEach(function (pacote) {
                if (condition)
                    filtered.push(pacote);
            });
            $scope.showMessage = false;
            return filtered;
        }, 3000);    
    })
    

    I was not able to test this since I don't have all of your code. But something like this should work assuming I have the syntax right. You would have to inject $scope and $timeout in the appropriate places for this to work though.

    Edit: I just realized escopo likely means scope in another language. Assuming that is true and you are actually passing in the scope, just put escopo where I have $scope.