2

Within a controller, I'd like to share data between two functions. For example:

controllers.controller('rightDrawerCtrl', function ($scope, $http) {
  $scope.shared_id;

  $scope.getId = function ()  {
  // get the id via $http, using a secondary id to retrieve the shared_id
  }

  $scope.useId = function () {
  // use the shared_id to make a different api call
  }

});

In this example however, when useId() is called, shared_id is undefined.

I presume this is because useId was 'created' while shared_id was undefined, so hasn't been notified of the new value.

The only way I've found to fix this is by using two controllers: Share data between AngularJS controllers

Is there a better way to do this, using only 1 controller?

1
  • if you must used this method, add a timeout around shared_id to init it first. Commented Mar 2, 2016 at 6:51

4 Answers 4

1
$scope.shared_id;

After the above statement the shared_id variable of $scope should be undefined - because you haven't assigned it any value.

Despite this the variable is still accessible inside any scope functions because $scope is global for them. And don't forget that you should access it like $scope.shared_id in all the places.

However if you initialize it in the following manner:

$scope.shared_id = 'no id';

.. it would not return undefined.

You can initialize this variable via ng-init too.

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

1 Comment

While that would stop it from returning 'undefined' - I cannot access any changes that have been made to the variable since init
0

Call userId() function when getId() function get result from $http request.

1 Comment

Unfortunately getId must be called independently of useId. I've adjusted the example to illustrate this.
0

Looks like I simply had to wrap the variable assignment in $scope.$apply

$scope.$apply(function() {
  $scope.shared_id = 1234;
});

Comments

0

You can use like this with this is much easier.

var self = this;
this.shared_id;


  $scope.getId = function ()  {
    console.log(self.shared_id) ;
  }

  $scope.useId = function () {
    console.log(self.shared_id) ;
  }

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.