Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
    
You can find a very clear answer posted here – Alankar Choudhary Jul 19 at 5: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. – think123 Jul 19 at 11:20
up vote 34 down vote accepted

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";        
}
share|improve this answer
    
What does $scope.user = User; without quotes do? – think123 Mar 22 '14 at 22:32
    
@think123: Its the service.... $scope.user = {} – Thalaivar Mar 23 '14 at 10:16
    
Ah, right. I also have a route parameter argument in ControllerA, so how would I add that in as well? – think123 Mar 24 '14 at 4:23
1  
what if i dont want to use service or factory ?? is there a way around – Sagar Devanga May 17 '14 at 13:09
2  
I know this is an older post but was a lifesaver! – aemorales1 Mar 3 at 20:47

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

share|improve this answer
    
An answering with an example is a more helpful answer – tno2007 Dec 2 '15 at 13:35
app.controller('foo2', function ($scope) {
    $scope.$$prevSibling.bar="bar"
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.