1

I have a custom directive with next params

 return {
        scope: {
            ngModel: '='
        },
        require: "ngModel",
        link: function (scope, element, attrs, ngModel) {
    // directive code ...
}

and two templates which are using this directive

//template 1
  <div class="panel-body">
       <div ng-include src="'email.html'"></div>
  </div>

// email.html 
  <div id="template"
       ng-model="emailNotification"
       custom-directive></div>

// template 2
  <div class="panel-body">
       <div ng-include src="'sms.html'"></div>
  </div>

// sms.html 
  <div id="template"
       ng-model="smsNotification"
       custom-directive></div>

The problem here when I toggle between these two templates, ng-model inside 'custom-directive' doesn't refresh and value shares between two different ng-models. However I would like that directive wouldn't do that.

Where is my mistake and why does directive share this variable?

1
  • What do you mean by toggle between these two templates? Can you please set up a working fiddle to illustrate the problem you are facing? Commented Aug 9, 2017 at 19:14

2 Answers 2

1

When you use the = operator the directive's scope property binds to the parent's scope property by the same name. Since you are using ng-model on both instances of the directive inside the same parent, they both end up referencing the same ng-model.

If you want the evaluated value of the property from the parent scope, use @ binding.

return {
        scope: {
            ngModel: '@'
        },
        require: "ngModel",
        link: function (scope, element, attrs, ngModel) {
    // directive code ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

So simple, this solved my problem! Thank you a lot, I appreciate it!
1

There are several different forms of scope for directives. You can use them all depending on the outcome you are expecting. They are scope: true, scope: {}, scope: false.

Each scope acts differently. The scope you are looking for is scope: {}, or scope: true.

If you do use scope: {} you want to ensure that the elements within are using the proper syntax =, @ and &. In your case you will want to use the @ symbol.

Explanation of symbols: Explanation

@: Pass this attribute as a string =: Data bind this property to the directive's parent scope. &: Pass in a function from the parent scope to be called later. Used to pass around lazily evaluated angular expressions.

Comments

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.