Elnaz Elnaz - 1 year ago 103
jQuery Question

Caching dropdown options in AngularJS - SPA

I have a form which has 3 parts (field name, operator, value). The third part will be shown based on type of the selected value of first drop down.

enter image description here
enter image description here

This rows can be added with an add button.

If I had similar selections in first drop downs (which need similar drop down in third part) I would have similar drop down options in third part.

For example, If the user select city of birth and residence city in first column of first and second row, we need list of cities, in third column of rows, both.

In this cases I don't want to send a request to server.

Also if it's possible I don't want to call the service function from the controller.

what is the best was in this case and how I Can implement that?


When a dropdown want to be initialized:

  • If the options values exist in cache, use them.

  • else:

    • send a request to server and get the values

    • cache the data for next time

Answer Source

For this purpose, I used angular-cache and used angular-cache.min.js.

More Info:

I injected the 'angular-cache' service into my module.
Then, injected 'CacheFactory' to my AngularJS service. Also I needed '$q' to make a response object.

function angularCacheSampleService($http, $q, cacheFactory, adminApiRoot) {
  var self = this;
  self.cacheList = cacheFactory('urlResponseCache', { maxAge: 300000, deleteOnExpire: 'aggressive' });

self.angularCacheSampleCompleteCode = function (dataSource) {

            var deferred = $q.defer();
            //read from cache
            var responseList = self.cacheList.get(dataSource);
            if (angular.isUndefined(responseList)) {
                //not found in cache
                self.apiResponse = $http({
                    method: 'GET',
                    cache: false,
                    url: dataSource

                  .then(function (response) {
                  self.cacheList.put(dataSource, response);
               }, function (response) {

            } else {
                //found in cache
            return deferred.promise;

Attention: If you make your cache ('urlResponseCache' in this code) inside your method, you will have runtime error since the cache has built before, so define that before the function.