Teja
Teja

Reputation: 133

Directive inside templateUrl of another directive and passing attribute

I'm having two directives and I'm trying to call one directive inside another directive's templateUrl with some attribute but I'm not able to get the compiled attribute value in the second directive. Code is like this:

1st directive

app.directive('myDir', function() {
   return {
     link: function(scope, element, attrs, controller) {
         scope.myVal='hello';
     },
     templateUrl: 'directive1.html',
     scope: {}
  }

directive.html

<div>
   <child-dir attrval="{{myVal}}"></child-dir>
<div>

2nd directive

app.directive('childDir', function() {
       return {
         templateUrl: template(element,attrs) {
             alert(attrs.attrval);
         },
         scope: {}
      }

Here, attrs.attrval is coming like this {{myVal}}. but I want the value hello. Can anyone help me? Please note two things here:

1) I'm using templateUrl. 2) I'm passing a scope variable's value as an attribute to the child directive.

Upvotes: 3

Views: 705

Answers (1)

AliMola
AliMola

Reputation: 578

I had the same problem and finally found the solution (probably not the best, but it's working for me). Your example is a litte bit different from mine, but I suppose in your example would be:

Parent directive and directive.html equals, but child directive:

app.directive('childDir', function() {
   return {
     templateUrl: template(element,attrs) {
           attrs.$observe("attrval", function(){
             alert(attrs.attrval);
           });
     },
     scope: {}
  }

When template is set in parent directive the value is not set yet, but child directive is trying to use it. With 'observe', child directive can force refresh when attrval is really set.

If not works for you, tell me and I will post parts of my code in case it would be useful.

Upvotes: 1

Related Questions