[英]Angular 1.x - Element appended on directive not rendering
I have this code where I'm trying to append a button to every input element on the page - if I inspect the dom, the button is there, but it is never rendered. 我有这段代码,试图在页面上的每个输入元素上附加一个按钮-如果我检查dom,则该按钮在那里,但从未渲染过。
<html>
<div ng-app="app">
<label for="input1">input1</label>
<input name="input1" type="text">
<br><br><br>
<label for="input2">input2</label>
<input name="input2" type="text">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('app', [])
.directive('input', function($compile) {
return {
restrict: 'CAE',
link: Link
};
function Link(scope, element, attrs) {
var elementAppend = '<button>X</button>';
var a_input = angular.element($compile(elementAppend)(scope));
element.append(a_input);
}
});
</script>
</html>
.append
tries to add the element inside the input element, which isn't supported. .append
试图将元件添加的输入元件,其不支持内部 。 An input
element can't have child elements. input
元素不能有子元素。 This restriction comes from HTML, not from AngularJS. 此限制来自HTML,而不是来自AngularJS。
Use element.after(a_input);
使用
element.after(a_input);
instead to add the button after the input element. 而是在输入元素之后添加按钮。
angular.module('app', []) .directive('input', function($compile) { return { restrict: 'CAE', link: Link }; function Link(scope, element, attrs) { var elementAppend = '<button>X</button>'; var a_input = angular.element($compile(elementAppend)(scope)); element.after(a_input); } }); angular.bootstrap(document.getElementById('app'), ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <html> <body> <div id="app"> <label for="input1">input1</label> <input name="input1" type="text"> <br><br><br> <label for="input2">input2</label> <input name="input2" type="text"> </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.