AngularJs - 在 $scope 变量准备好之前访问它的代码

AngularJs - Code accessing $scope variable before it is ready

我有一个控制器 (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
});

P.S:我不想将 rest of controller code 放在 success 块中

谢谢

选项-1:使用一些初始化函数

您可以将初始化逻辑移至名为 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;
    }

});

Option-2:使用 resolve

您还可以使用 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
});

有关此控制器激活和路由解析模式的更多信息,您可以参考this and this

希望这对您有所帮助:)