[英]How to add `<input>` elements with button click AngularJS
I want to be able to add a new element and use the ng-bind property to change the value of the new element. 我希望能够添加一个新元素并使用ng-bind属性更改新元素的值。
I've tried multiple things, please see the code below for the best I've been able to come up with. 我已经尝试了多种方法,请参阅下面的代码,以取得最好的结果。
$(document).ready(function() {
$("#create-input").click(function() {
var newInput = document.createElement("p");
var code = document.createElement("span");
code.innerHTML = "{{input2}}";
newInput.innerHTML = "<p>{input2}: <input type='text' ng-model='name2'>  {{name2}}</p>";
$("#target-container").append(newInput);
$("#main-container").append(code);
});
});
When I add text the newly appended input, the appended {{name2}}
value does not change. 当我在新添加的输入中添加文本时,添加的{{name2}}
值不会更改。 I do not understand why I am unable to change {{name2}}
via the text input box after appending. 我不明白为什么添加后无法通过文本输入框更改{{name2}}
。
Use the ng-repeat
directive to add input elements to the DOM: 使用ng-repeat
指令将输入元素添加到DOM:
angular.module("app",[]) .controller("ctrl",function($scope) { $scope.arr=[ {name: "name1", value: ""} ]; $scope.addInput = function() { $scope.arr.push( { name: "name" + ($scope.arr.length+1), value: "" }) }; })
<script src="//unpkg.com/angular/angular.js"></script> <body ng-app="app" ng-controller="ctrl" > <div ng-repeat="elem in arr"> {{elem.name}}: <input ng-model="elem.value"> </div> <button ng-click="addInput()">Add Input</button> <div>{{arr}}</div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.