我是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 ) { } }; });
我无法弄清楚如何实现这一目标。
好吧,这个错误是不言自明的。您的模板需要具有一个根,而您的必须具有两个根。解决此问题的最简单方法是将整个内容包装在a div或a中span:
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>