简体   繁体   中英

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. 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.

Once the request is complete you can access $scope.result within the controller. 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. 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.

Here is a link that explains this concept: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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