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?

2
  • You can find a very clear answer posted here Commented Jul 19, 2016 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. Commented Jul 19, 2016 at 11:20

4 Answers 4

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";        
}
Sign up to request clarification or add additional context in comments.

5 Comments

What does $scope.user = User; without quotes do?
Ah, right. I also have a route parameter argument in ControllerA, so how would I add that in as well?
what if i dont want to use service or factory ?? is there a way around
@SagarDevanga: Pub/Sub Model
I know this is an older post but was a lifesaver!
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.

1 Comment

An answering with an example is a more helpful answer
5
app.controller('foo2', function ($scope) {
    $scope.$$prevSibling.bar="bar"
});

Comments

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;
    })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.