Optional two-way binding on isolate scope for Angular Directive

jusopi picture jusopi · Nov 7, 2014 · Viewed 16k times · Source

question

I just learned that you can have an optional 'reverse' or callback binding via:

scope: { parentScopeFunc: '&?' }

I'm trying to see if there is a way to do something similar with the 2-way binding.

scope: { optional2WayBoundProp: '=?' }

I tried with the link function's element & attrs params but then I lose the 2-way-binding back to the parent. That method only allows for parent-to-child updates. Then I might as well just be using @ scope mechanism.

edit

I found this question Angular JS directive, change a 2 way data binding in the link function so that answers the main question regarding =?. However it doesn't solve the 'optional' non-bound value such as true or false.

goals

Here's what I'm trying to accomplish:

  • write a panel directive that transcludes content and is collapsible aside from the header area:
    <my-panel> <transcluded-header-content/> <button ng-click="toggleCollapse()"/> <transcluded-body-content ng-if="isExpanded"/> </my-panel>

  • in some cases I want to cache the collapsed state of the panel instance in a parent scope (hence the 2-way binding where the view's controller can determine how to cache this info):

    <my-panel is-expanded="parentScopeProp">

  • in other cases, I may just want to declare it without binding to a parent scope property OR I may just not declare it at all in which case it assumes it's expanded.

    <my-panel is-expanded="true/false">

I understand that by using the = assignment, that expressions like undefined, true & false cannot be evaluated.

Answer

jusopi picture jusopi · Nov 11, 2014

'=?' is a valid scope assignment as of ng 1.2.x...

...as for the ability to have a means of interpolating an expression from an optional two-way-binding, that is still up for grabs.