2

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.

2
  • Try scope.someProperty = "New Value"; and override it whenever necessary. Since angular is two way binding scope.someProperty = scope.someProperty || "New Value"; will bring unnecessary confusions. Commented Mar 31, 2015 at 10:38
  • Isolate scope prevents unnecessary confusions. Angular is not always two-way data binding – @ is for one way binding Commented Mar 31, 2015 at 11:02

1 Answer 1

4

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";
  }
})
Sign up to request clarification or add additional context in comments.

8 Comments

This sounds very reasonable... do you have any solution for me? how can I give default values to optional attributes?
@user2717436, Please check the updated answer and plnkr.
Is this solution going to have a significant impact on the performance?
Do you have any documentation that confirm it? something I can show my managers for evidence?
I don't have any documentation to confirm it.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.