javascript - 指令模板必须只有一个根元素

标签 javascript angularjs angularjs-directive

我是 angularJs 的新手。我正在尝试创建包含输入元素和按钮的新指令。我想使用此指令在单击按钮时清除输入文本。

当我在 html 中使用指令时,出现以下错误:

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 ) {

    }
};
});

我不知道如何实现这一目标。

最佳答案

嗯,这个错误是不言自明的。您的模板需要有一个根,而您的模板有两个。解决此问题的最简单方法是将整个内容包装在 divspan 中:

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>',

之前:

<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>    <!--  <- 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>

关于javascript - 指令模板必须只有一个根元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992470/

相关文章:

javascript - 如何在模态对话框中获取选中的复选框行数据?

angularjs - ng-model 不适用于 select 指令

AngularJS 在指令中使用常量

javascript - Google Maps API - 无法在多个标记上设置多个 infoWindows

javascript - 如何使横幅图像在移动站点中下降

javascript - Clojure 到 JavaScript

javascript - 当Web请求出现错误时,是否可以不执行 Controller 中的promise(.then())?

angularjs - 为什么在 ng-include 中通过 onLoad 传递变量时只能在模板中访问?

Javascript 警报消息包含 URL

html - 如何强制 ng-style 添加到现有样式?