user2717436
user2717436

Reputation: 795

AngularJS directive with isolated scope - default attributes values

I have a directive with isolated scope. In the scope there is a property - passed as a string ('@').

This attribute is optional - I want to set some default value to the property if no value is passed in the directive attributes. So I've written the following line of code:

scope.someProperty = scope.someProperty || "New Value";

But this does not work as I expected... the scope.someProperty remains empty.

I explored around a bit and understand that one way binding to isolated scope property (@) means that the parent value can be read but not write into. what I wish to do is to set the local directive property value and not to change the parent.

How can I do it?

Please see an example in this plunker.

Upvotes: 2

Views: 938

Answers (1)

Vinay K
Vinay K

Reputation: 5572

Take a look at this plnkr

scope.someProperty = scope.someProperty || "New Value";

This assignment will set the someProperty value to New Value. But after the initial digest cycle because of scope: {someProperty: '@'} statement, angular updates the someProperty value to the corresponding attribute value which is empty.

Try this to provide the default value.

attrs.$observe('someProperty', function (nv, ov) {
  if (!nv) {
    scope.someProperty = "New Value";
  }
})

Upvotes: 4

Related Questions