简体   繁体   English

在angular之外访问Factory的回调函数内部的变量

[英]Accessing a variable inside a Factory's callback function outside of it in angular

My Factory looks like this: 我的工厂如下所示:

.factory('MyFactory', function(){
    return: {
         someFunction: functon(firstParam, secondParam, resultObject) {
                     $http.get(url).success(resultObject);
        }     
    }
})

My controller looks like this: 我的控制器如下所示:

.controller('MyCtrl', function($scope) {
    MyFactory.someFunction(paramOne, paramTwo, function(resultObj) {
          $scope.result = resultObj;
          console.log($scope.result) //has the object
     });
    console.log($scope.result) //undefined
}):

I'd like $scope.result to be available inside the controller and not just within the callback. 我希望$scope.result在控制器内可用,而不仅仅是在回调内可用。 Right now its only available within the callback function. 现在,它仅在回调函数中可用。

I understand what the problem is here, that the scope of the variable inside the callback function ends within the function, I just don't understand how to overcome this. 我了解问题出在哪里,回调函数内部的变量范围在函数内结束,我只是不知道如何克服这个问题。

The problem is not that the scope of the variable is within the callback function, the problem is that while you do console.log($scope.result) outside the function inside the controller the $http request has not been completed so it will be undefined. 问题不在于变量的范围是否在回调函数之内,而是在于当您在控制器内部的函数之外执行console.log($ scope.result)时,$ http请求尚未完成,因此它将未定义。

Once the request is complete you can access $scope.result within the controller. 请求完成后,您可以在控制器内访问$ scope.result。 The best way to solve this is to ensure that the $http request is finished before your controller even loads and this is possible through use of the resolve function in the routes. 解决此问题的最佳方法是确保$ http请求在控制器加载之前完成,这可以通过在路由中使用resolve函数来实现。 You would fire off the $http request and wait for it to complete before even loading the route, so the result could be directly injected into the controller. 您将触发$ http请求,并等待其完成,甚至没有加载路由,因此结果可以直接注入到控制器中。

Here is a link that explains this concept: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx 以下是解释此概念的链接: http : //odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM