【问题标题】:AngularJs - Code accessing $scope variable before it is readyAngularJs - 在准备好之前访问 $scope 变量的代码
【发布时间】:2015-12-28 04:45:33
【问题描述】:

我有一个控制器 (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 块内

谢谢

【问题讨论】:

  • 你用的是angular-router还是ui-router?
  • 我正在使用 routeProvider
  • 你不能将所有初始化逻辑包装在一个函数中,然后在你的成功回调中调用该函数吗?
  • @Arkantos 我可以做到。 .控制器代码的其余部分具有多个功能和代码块,具体取决于$scope.input。所以我担心将所有这些都放在一个函数中是否对我来说有意义
  • 事实上,您已经将所有逻辑放在了控制器函数中:) 通过上述建议的更改,您将在控制器中嵌套函数。现在您需要等待一些异步调用响应,我认为这是处理此问题的最简单方法。如果您愿意更换您的路由器,ui-router 有一个 resolve 功能可用于此类场景。

标签: javascript angularjs model-view-controller angularjs-scope http-get


【解决方案1】:

选项 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;
    }

});

选项 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

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多