AngularJS: How can I plug a directive into a template?

154 views Asked by At

I'm trying to write a generic confirmation screen. I'd like to reuse it across a variety of different entities. Each entity has a different directive used to render it to screen.

Is there a way to write a template with a "directive-shaped hole" (my-directive below) that I can fill in programmatically?

<div>
  Are you sure you want to blah?
  <directive-from-scope value-from-scope="theValue" params-from-scope="theParams" />
</div>
2

There are 2 answers

0
Vitalii Chmovzh On

I solve it with built-in ng-include directive.

Assume you have some directive with getTemplateUrl() function. You can put any login into this function but it should basically return you a string with the template URL.

Then you can do next thing in your directive template.

<div ng-include="directiveCtrl.getTemplateUrl()"></div>

Tag that you use doesn't matter, it can be any HTML tag, just choose one that works better for you.

Now in each template you can have whatever you want: directive, HTML with some controller on it, etc.

0
Slava Utesinov On

You can create directive with transclude:

angular.module('app', []).directive('myDirective', function() {
  return {    
    restrict: 'E',
    transclude: true,    
    template: `
    <div class='borders'>
      Are you sure you want to blah?
      <div ng-transclude></div>
    </div>
    `
  };
}).controller('ctrl', function($scope){
  $scope.log = console.log;
  $scope.title = 'Simple title';
});
.borders {
  border-style: solid;
  border-width: 1px 1px 1px 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <my-directive>
    <ul>
      <li>first</li>
      <li>second</li>
    </ul>  
    <input type='button' value='Log' ng-click="log(title)"/>
  </my-directive>
  <my-directive>
    <h4>{{title}}</h4>    
  </my-directive>
</div>