2015-10-17 45 views
2

我在我的工廠有一個函數需要第二個執行,我希望調用函數等待輸出完成之前console.log結果。當我運行getCases函數時,我沒有得到輸出,直到我再次點擊它。我想我使用我的承諾是錯誤的。如何等待工廠函數完成並在Angular中處理輸出?

app.factory('cases', function ($q) { 
    return {  
     getCases: function() { 
      var defer = $q.defer(); 

      setTimeout(function(){ 
       output = 'aaaa'; 
       defer.resolve(output); 
      },1000); 

      return defer.promise; 
     } 
    }; 
}); 


function CaseloadCtrl($scope, cases){ 
    $scope.master = {}; 
    $scope.activePath = null; 

    $scope.getCases = function(){ 
     cases.getCases().then(function(data) { 
      console.log(data); 
     }); 
    }; 

} 

按鈕

<button ng-click="getCases()">load cases</button> 
+1

這應該工作...'的console.log(數據)'將1秒後調用。無需第二次點擊 –

+0

對,請看下面我的小提琴。你能給我們你的完整代碼嗎? –

回答

-1

編輯:

新小提琴

http://jsfiddle.net/chrislewispac/f18taw28/1/

你的版本相同的結果。

http://jsfiddle.net/chrislewispac/f18taw28/2/

代碼:

<div ng-app='myApp' ng-controller="MyCtrl"> 
<button ng-click="runFunc()">Run Func</button> 
</div> 

var myApp = angular.module('myApp',[]); 

myApp.factory("cases", ['$q', '$timeout', function ($q, $timeout) { 
    return { 
     getCases: function() { 
     var defer = $q.defer(); 

     setTimeout(function(){ 
      output = 'aaaa'; 
      defer.resolve(output); 
     },500); 

     return defer.promise; 
     } 
    }; 
}]); 

myApp.controller('MyCtrl', function($scope, $q, cases) { 
    $scope.runFunc = function(){ 
     $q.when(cases.getCases()).then(function (result) { 
     console.log(result); 
    }); 
    }; 
}); 
+0

奇怪你的小提琴工作正常,但當我使用的代碼,狀態不會更新,直到我點擊一個按鈕,即使按鈕沒有做任何事情? {{status}}

+0

好的,我會檢查您的具體情況。無論如何,我應該這樣做。我會發佈一個新的小提琴。 –

+0

@MattH請檢查新的小提琴。 –