31

I have this:

app.controller('foo1', function ($scope) {
  $scope.bar = 'foo';
});
app.controller('foo2', function ($scope) {
  // want to access the $scope of foo1 here, to access bar
});

How would I accomplish this?

Lucas
  • 16,930
  • 31
  • 110
  • 182
  • You can find a very clear answer posted [here](http://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers) – Alankar Choudhary Jul 19 '16 at 05:50
  • @AlankarChoudhary Ah yes, though the accepted answers for the questions seem to vary a fair bit, so perhaps this does not warrant a close. – Lucas Jul 19 '16 at 11:20

4 Answers4

40

You could use an Angular Service to share variable acrosss multiple controllers.

angular.module('myApp', [])
.service('User', function () {
    return {};
})

To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.

function ControllerA($scope, User) {
    $scope.user = User;
    $scope.user.firstname = "Vinoth";
}

function ControllerB($scope, User) {
    $scope.user = User;
    $scope.user.lastname = "Babu";        
}
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
11

You just can use $emit/$broadcast for translate changes of data from one controller scope to another. Or just store these variables on $rootScope.

Sergey Moiseev
  • 2,953
  • 2
  • 24
  • 28
5
app.controller('foo2', function ($scope) {
    $scope.$$prevSibling.bar="bar"
});
ericj
  • 2,138
  • 27
  • 44
0
app.controller("firstCtrl", function ($scope) {
    $scope.func = function () {
        // pass scope variable(s) here
        $scope.$broadcast('parentmethod', { key: value });
    }
})

app.controller("secondCtrl", function ($scope) {
    $scope.$on('parentmethod', function (event, args) {
        // access scope variable using args
        $scope.targetVar = args.key;
    })
})
Stone
  • 583
  • 6
  • 8