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?

Community
  • 1
  • 1

4 Answers4

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.

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • While that would stop it from returning 'undefined' - I cannot access any changes that have been made to the variable since init – SpottedMagpie Mar 02 '16 at 07:51
0

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

0

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

$scope.$apply(function() {
  $scope.shared_id = 1234;
});
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) ;
  }
Minkyu Kim
  • 1,144
  • 3
  • 18
  • 43