Search code examples
javascriptangularjsangular-directiveangular-components

one-way binding does not work when binding item is object and modified dynamically


please see the plnkr for reviewing the code.

I really new in AngularJS component. I write two simple AngularJS components with exactly same binding .

 bindings: { value:'@', field:'@', object: '<', callback: '&' }   

I pass a Javascript object into my components by object. The field specifies the name of property in my JS object. Finally, value refers to the new value of JS object's property.

object[field] = value

If the component does not clone the object in its controller, one-way binding does not work (see onewaybindingfail component in the plnkr). However, by cloning the object in component's controller everything is fine.

I would like to know this behavior is expected? if yes, why? or I missing something?.

Thanks for your help.


Solution

  • This behaviour is expected. Denoting a one way binding with "<" simply means that angular will not watch for changes on the component side, but if you change the object on the component side the original object will still be modified. This is also mentioned in the official angular documentation here.

    Therefore it's recommended to make a copy of the object if you need work with it. Preferably you'd work with callback function to make changes to the parent object. This is also explained in more detail in the official angular documentation.