hguser
hguser

Reputation: 36038

Get directive element and template element both for compiling directives

I want to create a directive which itself can be inserted into the template, like this:

(function() {
  function FormInputDirective() {
    return {
      replace: true,
      scope: {
        label: "@"
      },
      compile: function(tElement, tAttrs) {
        //tElement.find(".input-container").append(directiveElement);

        var link = function($scope, element, attrs) {
          //....
        };
        return link;
      },
      templateUrl: 'form-input.html'
    }
  }
  angular.module("mainApp", []).directive("formInput", [FormInputDirective]);
})();

template:

<div class="form-group input-container">
    <label>{{label}}</label>
    <!-- where the directive element to be inserted -->
</div>

usage:

<input type="number" ... form-input label="Name:" />
<input type="text" ....  form-input label="address:" min-length=... />
<textrea ................form-input label="Description" .......
....

expected result:

<div class="form-group input-container">
    <label>Name</label>
    <input type="number" ... form-input label="Name:" />
</div>
<div class="form-group input-container">
    <label>Name</label>
    <input type="text" ... form-input label="Address:" />
</div>

.................. Live demo

However if I want to make it work, I will have to get both the directive element and the template element which I have no idea at the moment. Since once the directive have a template, then the first argument passed to the compile function will be the template element, I can not find a way to get thedirective element`.

And I also know I can use ng-tranclude, however I will have to write extra elements like this:

<any-dir>
   <input ...... />
</any-dir>

I want to avoid this.

Is this possible?

Upvotes: 2

Views: 866

Answers (1)

Moncef Hassein-bey
Moncef Hassein-bey

Reputation: 1361

You can use tranclude : 'element'

From angular docs :

'element' - transclude the whole of the directive's element including any directives on this element that defined at a lower priority than this directive. When used, the template property is ignored.

a working demo using your exemple

Upvotes: 1

Related Questions