Sharing a variable between controllers in angular.js

Use a service and inject it to both controllers and refer your scope vars to the services variable.

Example:

angular.module("yourAppName", []).factory("myService", function(){

  return {sharedObject: {data: null } }

});

function MainCtrl($scope, myService) {
  $scope.myVar = myService.sharedObject;
}

function SearchCtrl($scope, $http, myService) {
  $scope.myVar = myService.sharedObject;
}

In your template do:

{{myVar.data}}

See an example Uses Angular v1.1.5

The reason you put it in an inner object is to preserve your references, if you keep it without a “sharedObject”, and change that object, your binding will be pointing to the old reference and wouldn’t show anything in the template.

Leave a Comment