Rivi
Rivi

Reputation: 791

Question mark in AngularJs directive

I have seen some directive using question mark ('?') in the scope properties definition like so:

    app.directive('userInfo', function() {
        return {
        restrict: 'A',
        scope: {prop: '=?'},
        templateUrl: 'some/template/url',
    };

I have looked for it and the only think i saw was this : what's the meaning of '=?' in angularJS directive isolate scope declaration?. But it's not working the way he explains it there. I have succeeded running my application and no Exception was thrown.

Can somebody elaborate more about it?

Upvotes: 11

Views: 5870

Answers (1)

Oliver Salzburg
Oliver Salzburg

Reputation: 22099

If you don't add the ? and don't put a prop property on your element you're using the directive on, then an exception will be thrown.

Adding the ?, marks the property as optional. As mentioned in the documentation for $compile:

You can avoid this behavior using =? or =?attr in order to flag the property as optional.

I think the documentation might be a bit outdated in that area. NON_ASSIGNABLE_MODEL_EXPRESSION only appears in older revisions of the source.

Please note that the exception is only thrown once you try to write to the scope property. I threw together a quick plunkr to showcase the issue: http://plnkr.co/edit/hjUq6ZisuRG2C3mZpRDj?p=preview

Upvotes: 13

Related Questions