到目前爲止,學習現有的stackoverflow答案總是幫助我,我總能找到答案,但現在我真的被卡住了。如何確保工廠承諾在指令執行前解決
我正在構建一個應用程序,它使用指令來創建日曆月類型框。
<app2directive class="column_50" jahr="2016" mon="November"></app2directive>
因此該指令代碼隔離範圍和利用templateUrl文件提請日曆月
App.directive('app2directive',function(YEARS, MONTHS, DAYS){
return {
restrict:"ACE",
scope:{},
replace:true,
templateUrl:"templates/cal_directive3.html",
controller: function ($scope, $attrs, $injector, $log, YEARS, MONTHS, DAYS) { var factoryName = "datumFactory" ;
var factoryTonnen = "jsonsrc" ;
var factoryInstance = $injector.get(factoryName) ;
var tonnenInstance = $injector.get(factoryTonnen) ;
var wtf = $scope.jsondata.get().then(function(promise){
console.log("jsondata", promise) ;
//$scope.tonnen = promise ;
}, function(error){
console.log("error", error) ;
}) ;
});
在我使用$注射器注入工廠運行在$ http請求的那一刻閱讀帶有數據的json文件,例如假期或特定於所選年份和月份的其他靜態信息。
App.factory('jsonsrc', function($http, $q){
return {
get: function(){
var deferred = $q.defer() ;
$http.get('termine_2016.json')
.success(function(data, status, headers, config) {
deferred.resolve(data) ;
}).error(function(data, status, headers, config) {
console.log("[jsonsrc] request didnot work!");
deferred.reject(data) ;
}) ;
return deferred.promise ;
}
}
});
它的效果是,對$ http的同一調用運行12次全年頁面加載。
我的問題是重構文件,以便我可以優先將json數據加載到主控制器中,並且指令作用域可以從父作用域繼承。
就其性質而言,該呼叫返回承諾。該指令需要等待這個承諾才能解決的方法,但現在我被困在如何去解決這個問題上。提前感謝任何指針!