Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One way to share variables across multiple controllers is to <a href="https://code.angularjs.org/1.2.21/docs/guide/services" rel="noreferrer">create a service</a> and inject it in any controller where you want to use it.</p> <p><strong>Simple service example:</strong></p> <pre><code>angular.module('myApp', []) .service('sharedProperties', function () { var property = 'First'; return { getProperty: function () { return property; }, setProperty: function(value) { property = value; } }; }); </code></pre> <p><strong>Using the service in a controller:</strong></p> <pre><code>function Ctrl2($scope, sharedProperties) { $scope.prop2 = "Second"; $scope.both = sharedProperties.getProperty() + $scope.prop2; } </code></pre> <p>This is described very nicely in <a href="http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/" rel="noreferrer">this blog</a> (Lesson 2 and on in particular).</p> <p>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. </p> <p>Example: <code>var property = { Property1: 'First' };</code> instead of <code>var property = 'First';</code>.</p> <hr> <p><strong>UPDATE:</strong> To (hopefully) make things more clear <a href="http://jsfiddle.net/b2fCE/1/" rel="noreferrer">here is a fiddle</a> that shows an example of:</p> <ul> <li><strong>Binding to static copies of the shared value (in myController1)</strong> <ul> <li>Binding to a primitive (string)</li> <li>Binding to an object's property (saved to a scope variable)</li> </ul></li> <li><strong>Binding to shared values that update the UI as the values are updated (in myController2)</strong> <ul> <li>Binding to a function that returns a primitive (string)</li> <li>Binding to the object's property</li> <li>Two way binding to an object's property</li> </ul></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload