Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 995
Vish021 Avatar asked Jan 16 '15 20:01

Vish021


2 Answers

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>
like image 139
JLRishe Avatar answered Oct 16 '22 15:10

JLRishe


This error will also occur if the path to the template is incorrect, in which case the error is everything but explanatory.

I was referring the template from within templates/my-parent-template.html with the (incorrect)

template-url="subfolder/my-child-template.html"

I changed this to

template-url="templates/subfolder/my-child-template.html"

which solved it.

like image 24
Frederik Struck-Schøning Avatar answered Oct 16 '22 15:10

Frederik Struck-Schøning