SpottedMagpie SpottedMagpie - 1 month ago 5x
AngularJS Question

angularjs share variable between functions

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

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

$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?


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

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