Recent Posts

Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

Angular JS: How to pass variables between controllers

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:

Binding to static copies of the shared value (in myController1)

  • Binding to a primitive (string)
  • Binding to an object's property (saved to a scope variable)

Binding to shared values that update the UI as the values are updated (in myController2)

  • Binding to a function that returns a primitive (string)
  • Binding to the object's property
  • Two way binding to an object's property