javascriptangularjsangularjs-controller

AngularJS: How can I pass variables between controllers?


I have two Angular controllers:

function Ctrl1($scope) {
    $scope.prop1 = "First";
}

function Ctrl2($scope) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

I can't use Ctrl1 inside Ctrl2 because it is undefined. However if I try to pass it in like so…

function Ctrl2($scope, Ctrl1) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

I get an error. Does anyone know how to do this?

Doing

Ctrl2.prototype = new Ctrl1();

Also fails.

NOTE: These controllers are not nested inside each other.


Solution

  • One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.

    Simple service example:

    angular.module('myApp', [])
        .service('sharedProperties', function () {
            var property = 'First';
    
            return {
                getProperty: function () {
                    return property;
                },
                setProperty: function(value) {
                    property = value;
                }
            };
        });
    

    Using the service in a controller:

    function Ctrl2($scope, sharedProperties) {
        $scope.prop2 = "Second";
        $scope.both = sharedProperties.getProperty() + $scope.prop2;
    }
    

    This is described very nicely in this blog (Lesson 2 and on in particular).

    I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.

    Example: var property = { Property1: 'First' }; instead of var property = 'First';.


    UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of: