我是 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 ) {
}
};
});
我不知道如何实现这一目标。
最佳答案
嗯,这个错误是不言自明的。您的模板需要有一个根,而您的模板有两个。解决此问题的最简单方法是将整个内容包装在 div
或 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>',
之前:
<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/