Angular one-way binding in component setting value in parent, why?

时间:2018-01-21 02:48:34

标签: angularjs angular-directive angular-components

I have a simple angular 1.5 component for a text field:

angular.module('myapp')
   .component('textComponent', {
      template: '<input type="text" ng-model="$ctrl.textfield.value" value="{{$ctrl.textfield.value}}">',
      bindings: {
        textfield: '<'
      }
    });

And I am using that component in a directive, in this html

<text-component textfield="form.textfield"></text-component>

When I enter a value in that textfield and save my form, it works. Sounds great right but why it is working? I thought components get their own scope by default and I thought that the '<' is a one way binding, preventing changes in a child from propagating back into the parent.

Looking at angular docs I see:

one-way binding does not copy the value from the parent to the isolate scope, it simply sets the same value. That means if your bound value is an object, changes to its properties in the isolated scope will be reflected in the parent scope (because both reference the same object).

Which now makes since, I am passing an object to the child as reference, as such properties in that object that are updated in the child will be reflected in the parent.

That leaves me with a couple questions.

Should one-way bindings only be used with primitives?

Is there any gain in using a one-way binding with an object?

0 个答案:

没有答案