129

Does the question mark after equals have special meaning? ie:

scope: {foo: '=?'}

does the above mean 'do not raise error if 'foo' cannot be resolved?

1 Answer 1

156

Yes:

The 'isolate' scope takes an object hash which defines a set of local scope properties derived from the parent scope. These local properties are useful for aliasing values for templates. Locals definition is a hash of local scope property to its source:

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <widget my-attr="parentModel"> and widget definition of scope: { localModel:'=myAttr' }, then widget scope property localModel will reflect the value of parentModel on the parent scope. Any changes to parentModel will be reflected in localModel and any changes in localModel will reflect in parentModel. If the parent scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You can avoid this behavior using =? or =?attr in order to flag the property as optional.

It should trigger the expected error on every digest that affects the scope property:

parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
     throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
     ' (directive: ' + newScopeDirective.name + ')');
};

//...


if (parentValue !== scope[scopeName]) {
    // we are out of sync and need to copy
    if (parentValue !== lastValue) {
        // parent changed and it has precedence
        lastValue = scope[scopeName] = parentValue;
    } else {
        // if the parent can be assigned then do so
        parentSet(parentScope, lastValue = scope[scopeName]);
    }
}
5
  • 1
    Makes sense but why doesn't this directive throw exception. parent scope property doesn't exist and scope assignment is NOT using a '=?'
    – Nikita
    Dec 9, 2013 at 17:32
  • 7
    It seems to only throw the error when the value is set, like here: plnkr.co/edit/OSpaC6sPE0hY9yAeFghr?p=preview Dec 9, 2013 at 21:05
  • @cebor It's currently linked in the answer, but here is a more direct link: docs.angularjs.org/api/ng/service/… Jul 25, 2015 at 23:44
  • 3
    Although personally I wish it were documented in the scope section directly and not in $compile. Jul 25, 2015 at 23:45
  • Thanks for the answer, I have been using angular for well over a year and never found the "=?" option on a directive. You just made my day ;-)
    – wilblack
    Feb 19, 2016 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.