14

Is there a good way to have AngularJS directives evaluate an attribute passed in as a parameter?

Here's a simplified example to show my problem (I recognize you could implement this behavior without a directive):

link: function postLink(scope, element, attrs) {    
      debugger; // scope.$parent already knows the value of teacher here
      scope.sendEmail = function(){
          alert(attrs.recipient);
          //window.open("mailto:" + attrs.recipient);
      }
    }

I would like the directive to use the value of teacher.email (note that the link function has the correct value for scope.$parent.teacher) instead of the string teacher.email.

1
  • 1
    just replace attrs.recipient with scope.recipient Commented Mar 19, 2013 at 18:26

1 Answer 1

23

As @Ajay already mentioned in a comment, you can use scope.recipient. This works because you created an isolate scope in your directive:

scope: {    
   recipient: "="
},

This creates a directive scope property named recipient which is two-way databound to a parent scope property. Which parent property? The one defined by your attribute: recipient="teacher.email" – hence parent scope property teacher.email is bound to isolate scope property recipient.

If your directive will not be altering the value of recipient, you should probably use '@' instead of '='. '@' gives us "one-way strings":

scope: {    
   recipient: "@"
},

You'll need to alter your HTML though:

<sendemail recipient="{{teacher.email}}"></sendemail>

In the sendEmail() function, we can still use scope.recipient, just like we did for '='.


If we use scope: true instead, the directive will create a "normal" child scope, rather than an isolate scope. In the directive we would then use

scope.$eval(attrs.recipient)

to obtain the value. This works because of the way JavaScript prototypal inheritance works. $eval will look for property teacher.email and not find it on the directive child scope. It then follows the prototype chain to the parent scope and finds it there.

Sign up to request clarification or add additional context in comments.

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.