Search code examples
angularjsajaxlazy-loadingchainingangular-filters

AngularJS - Delaying filter until after loading AJAX calls


I want to know how I can delay the filter functionality until after loading all the data through AJAX calls.

I'm trying to filter through data, but I can't filter some of them since they're not loaded until the AJAX calls. Is there a way to either delay the filter functionality or disable and enable it after all data is loaded?

Update

The way that the data structure is set up is that I make an AJAX call and load a list of posts made by different users. Afterwards, I call two other AJAX calls to load information about the user and the account for each post.

When I set up filters for posts + user info + account info, I can only filter through posts. However, I want to filter through user and account information as well.

I think I can fix the problem if I disable filters until all data is loaded.


Solution

  • Use ng-model plus the : syntax to bind the filter to the response data to do this. For example:

    <select ng-model="$root.listData" ng-include="'my_list' | filterTopTen:$root.listData" required></select>
    

    Many stateful filters can be converted into stateless filters just by exposing the hidden state as a model and turning it into an argument for the filter.

    Unit Tests reveal that filters are executed in the following cases:

    • should not invoke filters unless the input/arguments change

    • should reevaluate filters with non-primitive input that does support valueOf() when valueOf() value changes

    • should always reevaluate filters with non-primitive input that doesn't support valueOf()

    • should not reevaluate filters with non-primitive input that does support valueOf()

    • should always reevaluate filters with non-primitive input created with null prototype

    Since filters run before controllers, make sure the controller which updates the model is separate from the controller which is bound to the view to avoid a race condition.

    Filters with memoization can be used to avoid the digest cycle:

    Functional programming strives to minimize moving parts by building reusable mechanisms into the runtime. Memoization is a feature built into a programming language that enables automatic caching of recurring function-return values.

    Using functional-language features like memoization, I can add caching at the function level, achieving better results (with virtually no change to my code) than the imperative version. Functional programming eliminates moving parts, allowing you to focus your energy on solving real problems.

    References