Vish021 Vish021 - 5 months ago 72
Javascript Question

Template for directive must have exactly one root element

I am new to angularJs. I am trying to create new directive which contains input element and a button. I want to use this directive to clear input text when button is clicked.

When I use my directive in html I am getting below error :

Error: [$compile:tplrt] Template for directive 'cwClearableInput' must have exactly one root element.


html:

<div class="input-group">
<cw-clearable-input ng-model="attributeName"></cw-clearable-input>
</div>


clearable_input.js:

angular.module('cw-ui').directive('cwClearableInput', function() {
return {
restrict: 'EAC',
require: 'ngModel',
transclude: true,
replace: true,
template: '<input type="text" class="form-control"/><span class="input-group-btn"><button type="button" class="btn" ng-click="" title="Edit"><span class="glyphicon-pencil"></span></button></span>',
controller: function( $scope ) {

}
};
});


I am not able to figure it out how to achieve this.

Answer

Well, the error is pretty self-explanatory. Your template needs to have a single root and yours has two. The simplest way to resolve this would be to just wrap the whole thing in a div or a span:

template: '<div><input type="text" class="form-control"/><span class="input-group-btn"><button type="button" class="btn" ng-click="" title="Edit"><span class="glyphicon-pencil"></span></button></span></div>',

Before:

<input type="text" class="form-control"/>
<span class="input-group-btn">
  <button type="button" class="btn" ng-click="" title="Edit">
    <span class="glyphicon-pencil"></span>
  </button>
</span>

After:

<div>    <!--  <- one root   -->
  <input type="text" class="form-control"/>
  <span class="input-group-btn">
    <button type="button" class="btn" ng-click="" title="Edit">
      <span class="glyphicon-pencil"></span>
    </button>
  </span>
</div>