简体   繁体   中英

How to add `<input>` elements with button click AngularJS

How to use ng-bind in realtime after appending an object

I want to be able to add a new element and use the ng-bind property to change the value of the new element.

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}:&ensp;<input type='text' ng-model='name2'>&emsp; {{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. I do not understand why I am unable to change {{name2}} via the text input box after appending.

Use the ng-repeat directive to add input elements to the 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM