2013-07-03 22 views
1

我正在嘗試開發一個應用程序,其中一個模塊將依賴於第二個模塊。在第一個模塊運行函數中,我嘗試使用服務器中的一些數據填充templatecache HTTP但由於HTTP調用是異步我的第二個模塊之前,首先運行結束,我得到的結果不確定的。下面的代碼會使情況更加清晰如何在初始化之前等待依賴模塊運行功能

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 untill module main is finished running run function 
       alert($templateCache.get('ajay')); 
      }); 
+0

這就像你想要運行第二個應用程序第一個是回調。在主頁面上同時存在兩個應用程序會不會很糟糕,在第一個應用程序的成功回調中觸發'ng-if'加載第二個應用程序?我不知道,我還沒有試過.. – rGil

回答

1

擁抱異步:

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); 
    }); 
}); 
+4

擁抱異步性,是的,但不是它不存在的地方。 $ templateCache.get()不返回承諾,它返回數據。 –

相關問題