Understanding Factories

Sharing data between controllers

by marcio reis
Javascript: Objects passed as reference

Any singleton is passed as reference when it comes to javascript.

      var b = { name: 'Ricardo' }
      var a = b;
      //updating the property name of b.name to something else will cause the a.b to be updated. This is what happens when when we use factories. 
      
    
When does the reference stop working?

Whenever we try to bind an object to other object properties the reference is lost and changing values wont be reflected anymore without our intervention

      var b = { name: 'Ricardo' }
      var a = b;
      var c = b.name; //c is now 'Ricardo';
      c = 'Maria';
      // b.name is still Ricardo
      // a.name is still Ricardo
    

Example

Keep data sync using the object reference from here

This controller updates the property when we click the link 'update'
{{binValue.getByte();}} update The input value doesn't update when you write on the inputbox of the second example because it's a different property!


This controller has a two-way binding input between the input value and binFactory property 'byte' which causes other scopes that are bound to the same object reference to update automatically
{{binValue.getByte();}}


Failing Examples

{{binValue.getByte();}} update DON'T!!! This example binds the scope to different properties and methods of our factory. This breaks the object reference!


{{binValue.getByte();}} update DON'T: This example doesn't update when we change the value on the first 2 examples because it's bound to a property of the factory. ($scope.value = 'binFactory.byte'). But when we click the update button the first to examples are updated because we call the method setByte on it's own object reference