think123 think123 - 1 year ago 112
Javascript Question

How to share the $scope variable of one controller with another in AngularJS?

I have this:

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

How would I accomplish this?

Answer Source

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";        
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download