1

Is there any way to insert in a directive template an angular variable as a string? for example {{row.name}}, so that angular does not interpret it in the page only in the directive. something like this:

directive template:

<div>
   <div ng-transclude ng-repeat="row in data"> 
   </div>
</div>

A use case: I send to the directive from the controller the data array. person.name = "John", person.name = "Mike". For this case my page would look like:

....
<div my-directive>
   Name: {{row.name}}
</div>

From another controller i send the data: car.weight = 13, car.weight = 44 For this case my page would look like:

....
<div my-directive>
   Weight: {{row.weight}}
</div>

The result would be: Name: Name: or Weight: Weight:

This is because {{row}} is undefined

Is this possible or am I understanding everything wrong and there's another way?

1
  • YES, you can use like that... Commented Jan 21, 2015 at 21:17

1 Answer 1

2

You need to add row property to transclusion scope. This is because the scope of ng-transclude directive does not inherit from my-directive scope, but from outer (page) scope.

One way to do it is to create special transclusion directive:

module.directive('myDirectiveTransclude', function() {
  return {
    link: function($scope, elem, attrs, ctrl, $transclude) {
      $transclude(function(dom, transclusionScope) {
        transclusionScope.row = $scope.row;
        return elem.append(dom);
      });
    }
  };
});

Then replace ng-transclude with it:

<div>
    <div my-directive-transclude ng-repeat="row in data"> 
    </div>
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! just what i was looking for. Could you please explain step by step what myDirectiveTransclude does exactly?
@hhh3112 It will receive $transclude function which is responsible for rendering transcluded DOM provided by my-directive user (e.g. Name: {{row.name}}). Then it calls $transclude with single argument — a clone linking function, which in turn gets called with clone of transcluded DOM as first argument and transclusion scope as second.
@hhh3112 The $scope inside myDirectiveTransclude's link function is a child scope of ng-repeat scope (in fact, there will be as many calls to link as the number of items in ng-repeat), but it also prototypically inherits from it. The transclusionScope is also a child of ng-repeat scope, but it does not prototypically inherit from it; instead it inherits from outer scope — the one where your directive was placed.

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.