Stéphane de Luca
Stéphane de Luca

Reputation: 13583

How to write an angularjs directive that makes use of both scope and attributes and refer it thru compiled partial?

I want to write a directive which takes advantage of custom attributes, as follows:

<plant-stages
    title="Exploration<br/>du cycle de<br/>développement<br/>de la plante"
></plant-stages>

The controller is currently as follows:

app.directive('plantStages', function () {
    return {
        restrict: 'AE',
        templateUrl: 'corn.figure.plant.stages.html',
        link: function (scope, element, attrs) {
        scope.title = attrs.title;
        }
    };
});

The partial is as follows:

<figure class="cornStages">
    <div>
        <p>{{title}}</p>
    </div>
    <div ng-repeat="stage in stages">
        <div class="stage{{stage.stage}}"></div>
        <div>
            BBCH&nbsp;: {{stage.bbch}}<br/>
            {{stage.displayName}}
        </div>
    </div>
 </figure>

The partial makes use of some scope model variables. And {{title}} should support plain HTML injection out of the view which embeds it, hence should be compiled. I tried to support this but without success.

What modification should I make to have the HTML compiled?

A bonus question: when I pass the attribute in, I create a dummy title variable in the scope that persists where it should only be local. How would one make changes to handle this?

Upvotes: 0

Views: 94

Answers (1)

Sebastian
Sebastian

Reputation: 17433

If you want to wrap HTML in your custom directive take a look at the transclude option (see docs):

module.directive('myDirective', function() {
  return {
    restrict: 'E',
    transclude: true,
    template: '<div ng-transclude></div>'
  };
}); 

This enables you to place HTML within the directive tag which can be used in the template:

<div ng-controller="Controller">
  <my-directive>
    <h1>Test</h1>
  </my-directive>
</div>

In case you really want to pass HTML via an attribute use ng-bind-html. This requires the ngSanitize module:

module.directive('myDirective', function () {
  return {
    restrict: 'E',
    template: '<div ng-bind-html="title"></div>',
        scope: {
            title:'@'
        }
    };
});

I added this to your fiddle.

Upvotes: 1

Related Questions