Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

How to wait for dependent modules run function to be completed before initialization

I am trying to develop an app where one module will be dependent on second module. In the first module run function Im trying to fill templatecache with some data from server using http but since http calls are async my second module will run before the first is completed and I get undefined in the result. Below code would make situation more clear

   var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
              $timeout(function () {
                  $templateCache.put('ajay', 'ajay');
              }, 1000);
          }
          ]);

          var secondapp = angular.module('plunker', ['main']);
          secondapp.controller('test', function ($scope, $templateCache, $timeout) {
              // get me undefined i want to wait until module main is finished running run function 
              alert($templateCache.get('ajay'));
          });

Upvotes: 1

Views: 1665

Answers (1)

Karen Zilles
Karen Zilles

Reputation: 7671

Embrace asynchronicity:

 var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
     $templateCache.put('ajay', $http.get("/data/ajay"));
 }
 ]);

 var secondapp = angular.module('plunker', ['main']);
 secondapp.controller('test', function ($scope, $templateCache, $timeout) {
     $templateCache.get('ajay').then(function (data) {
         alert(data);
     });
 });

Upvotes: 1

Related Questions