hhh3112
hhh3112

Reputation: 2187

AngularJS : Injecting string in directive from controller

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?

Upvotes: 1

Views: 122

Answers (1)

aikoven
aikoven

Reputation: 549

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>

Upvotes: 2

Related Questions