Javascript 如何在单击按钮时在 angularjs 中动态添加输入字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29838059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:05:33  来源:igfitidea点击:

how to add input fields dynamically in angularjs on button click?

javascriptangularjsangularjs-directiveangularjs-scope

提问by user944513

I am trying to make a simple example in which an input field and a button field each time a user clicks on button.

我正在尝试制作一个简单的示例,其中每次用户单击按钮时都会有一个输入字段和一个按钮字段。

How can I get the text of the input field when the new button, which is present along with input field, is clicked?

单击与输入字段一起出现的新按钮时,如何获取输入字段的文本?

http://codepen.io/anon/pen/yNLGzx

http://codepen.io/anon/pen/yNLGzx

var app = angular.module('ionicApp',['ionic']);
app.controller('cntr',function($scope){
     $scope.addfield=function(){
       alert("how to add input field dyanmically")
     }

})

I don't know how to do this; in jQuery we can use the append function, like so

我不知道该怎么做;在 jQuery 中我们可以使用 append 函数,就像这样

$('.addcontend').append('<input \> <button>get input value</button>')

How can I acheive this using angularjs?

如何使用 angularjs 实现这一目标?

回答by Arun P Johny

What you can do is to use an array to represent the inputs then loop through the array and render it like

你可以做的是使用一个数组来表示输入然后遍历数组并渲染它

 <div class="addcontend">
   <div ng-repeat="item in inputs">
     <input ng-model="item.value"\> <button>get input value</button>
   </div>
  </div>

then

然后

  $scope.inputs = [];
  $scope.addfield=function(){
    $scope.inputs.push({})
  }

Demo: CodePen

演示:CodePen