2

I am new in angularjs and as starter i have a problem with accessing object outside then function. I have created a factory:

    var injectParams = ['$http'];
    var address = function ($http) {
    var factory = {};

    factory.get = function () {
        return $http({
            method: "POST",
            url: '/address',
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                service: 'address'
            }
        });
    };
  return factory;
 }

And a controller method:

   function getAddresses() {
        address_factory.get().then(function success(response) {
            $scope.billing = response.data.billing;
            $scope.shipping = response.data.shipping;
            console.log(response.data);

        }, function error(x) {
            console.log(x);
        });
    }
   getAddresses();

The question is how can i access $scope.billing object outside getAddresses function? I have read promises in angularjs but i don't understand how to use...

3 Answers 3

2

$scope variables are available outse the promise once everywhere in the controller...

Hence $scope.billing will be accessible in html and controller js both...

Sign up to request clarification or add additional context in comments.

3 Comments

What does this mean ... 'Hence $scope.billing will be accessible in html and controller js both' ? when i try to ouput $scope.billing or to find the length of this object outside the getAddresses function the result is empty. console.log($scope.billing); I mean i know in the html i can access objects but want to access in the controller.
It is because the promise is in the event loop and you are accessing before the event loop returns .. try using it inside $timeout
@Danish No, do not use $timeout. Use a then callback on the promise to run code when the value is available.
1

$scope.billing is accessible everywhere in the controller and the template bound to that controller. But the value of $scope.billing is dynamic, it is undefined until the factory-get Promise is resolved. To reflect a dynamic nature of $scope.billing in the template you may try following approach:

 function getAddresses() {
    $scope.loading = true;
    address_factory.get().then(function success(response) {
      $scope.billing = response.data.billing;
      $scope.loading = false;
      $scope.error = null;
    }, function error() {
      $scope.loading = false;
      $scope.error = true;
    });
  }
 getAddresses();

and then in the template:

<div ng-if="loading">
  Loading...
</div>
<div ng-if="!loading && error">
  Got an error!
</div>
<div ng-if="!loading && !error">
  Billing: {{billing}}
</div>

Also, you may use $scope.$watch in the controller to watch for $scope.billing changes:

// ...
getAddresses();

$scope.$watch('billing', function() {
  // $scope.billing has been changed
  console.log($scope.billing);
});

But I would recommend to do all necessary logic right in the success-callback of the Promise.then call.

4 Comments

Yes ,you are right.I understood the reason why this is happening.Do you have any pattern suggestion how to fix it.'To fix it' i mean how to use necessary logic inside success-callback?
@MrAlb There is nothing to fix, this is how the Promise work, so just put your logic in the watch-callback or in the address_factory.get success callback (I'd prefer the second option). Also, if you are ok with ES2017, you may try async-await syntax to make the code more synchronous-like.
Maybe im not explaining to well.I have created another pagination function in same controller.Idea is , i want to find the length of this of $scope.billing object, so i can use in the pagination function.I understood how promises works but if not find the length of this object i cant do pagination.I am sorry that i am spending your time.
@MrAlb Process the pagination only when the Promise is resolved. You may block pagination in the template via loading approach. And you may init your pagination logic on billing-watch callback or in address_factory.get success callback. If you still have problems with it, I would recommend to post a new question with more details related to pagination case.
0

$scope means the current scope that is the current area where some-controller.js & the some-view.html is accessible.

If you set any variable to $scope it will be accessible anywhere in the some-controller.js & some-view.html.

Suppose you set ng-controller to any div as <div ng-controller="SomeController">.....</div>. So any thing with $scope like $scope.something is set in controller will be accessible in the controller and withing this div too, because the scope of the controller is this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.