0

我有一個控制器(MyCtrl)。首先要做的是做一個http.get的調用並獲得響應並將其分配給$scope.input。控制器的其餘部分取決於$scope.input。但問題是控制器中的代碼嘗試在http調用完成之前訪問$scope.input

我該如何解決這個問題?

app.controller('MyCtrl', function($scope, $http, $routeParams, factory) { 
    factory.getInfo($routeParams.id) 
    .success(function(response) { 
     //The factory code make the http.get call 
      $scope.input = response; 
    }); 

    //Rest of code accessing $scope.input before it is ready 
}); 

PS:我不想放置rest of controller codesuccess塊內

感謝

+0

你使用角度路由器還是ui路由器? – Arkantos

+0

我正在使用routeProvider – user7

+0

不能將所有的初始化邏輯封裝在函數中,然後在成功回調中調用該函數嗎? – Arkantos

回答

1

選項1:使用一些intialize功能

您可以將您的初始化邏輯函數調用initialize(),然後在您的AJAX調用的成功回調函數中調用該函數。

app.controller('MyCtrl', function($scope, $http, $routeParams, factory) { 
    factory.getInfo($routeParams.id) 
    .success(function(response) { 
      initialize(response); 
    }); 

    function initialize(){ 
     /* Move only the logic that depends on response from AJAX call in to 
      this method. 

      All utility functions, event handlers on scope are still outside 
      this function 
     */ 

     $scope.input = response; 
    } 

}); 

選項2:使用決心

您也可以使用resolve功能加載所有的依賴初始化控制器像下面前。

在你的路由器配置

$routeProvider 
     .when('/home/:id', { 
      templateUrl: 'home.html', 
      controller: 'MyCtrl', 
      resolve: { 
       factory : 'factory', 
       initData: function(factory,$route){ 
        return factory.getInfo($route.current.params.id); 
       } 
      } 
     }); 

在你的控制器

app.controller('MyCtrl', function($scope, $http, initData){ 
    $scope.input = initData; 
    // rest of your logic 
}); 

有關此控制器激活&路由解決模式的更多信息,你可以參考thisthis

希望這會有所幫助:)