Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5+ component optional one-way binding

Taken from the AngularJS 1 documentation:

You can also make the binding optional by adding ? : <? or <?attr.

How does the optional one differ from the non-optional one for the one-way binding?

I can seem to figure out the differences for the optional version of two-way (=) and delegate (&) bindings here on my fiddle: https://jsfiddle.net/glenn/ze2wo0s1/, but not for the one-way one.

By the way, a very Merry Christmas! 🎅🏻🎄❤️

like image 930
Glenn Mohammad Avatar asked Dec 24 '16 23:12

Glenn Mohammad


2 Answers

You can see the how it's handled in the source code: https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L3523.

To me, it looks like if you use <? and make the binding optional, it breaks early without setting up a watch. If use use < and make it required, it sets the binding to undefined and sets up a watch. However, it appears to be just watching undefined, so in practice, there's no difference at all except for that one call to recordChanges. In the case that you omit a required binding, the binding that's required will be a key in the changes object that is passed to $onChanges hook on the first call. However, when you omit an optional binding, it will not be a key in the changes object.

For an example see this JSFiddle. requiredBinding and optionalBinding are both omitted, and thus, initialized to undefined, but requiredBinding is a key on the change object, whereas optionalBinding is not.

like image 169
ppham27 Avatar answered Oct 22 '22 06:10

ppham27


Using <? makes it possible for the controller to change the value of the variable that was supposed to be bound, only if that variable is not present.

The optional bindings can be modified in the controller when they are NOT present. If the value is passed to the component, then there's no way of changing it.

The non-optional bindings can not be modified whatsoever. If they are not present, they are undefined and they can not be modified at all.

for example, assume you have this:

bindings: {
  nameOptional: '<?',
  nameRequired: '<'
}

In the controller, you can not simply do $ctrl.nameRequired = 'something else' and expect the view to get updated. However, you can do the same with nameOptional with one condition: only if name-optional is not passed to the component. Only then the variable is the controller's to change.

For better understanding you can refer this fiddle.

Note that to simplify the thing, we're using a string which is passed by value. If you are passing objects, the object's properties can always get modified in normal conditions.

like image 26
Aᴍɪʀ Avatar answered Oct 22 '22 06:10

Aᴍɪʀ