Angular 1.5+ component optional one-way binding

Glenn Mohammad picture Glenn Mohammad · Dec 25, 2016 · Viewed 8.4k times · Source

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! 🎅🏻🎄❤️

Answer

ppham27 picture ppham27 · Dec 25, 2016

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.