简体   繁体   English

如何在角度js中单击按钮添加和删除文本字段

[英]How to add and remove text field on click of a button in angular js

I have generated button using ng-repeat directive in angular js. 我在角度js中使用ng-repeat指令生成了按钮。 Now I want to generate a textfield inside a div tag on click of that button. 现在我想在点击该按钮时在div标签内生成一个文本字段。

Example buttons - 示例按钮 -

在此输入图像描述

Example textfields added on click of it - 点击它添加示例文本字段 -

在此输入图像描述

I am doing this using innerHTML attribute of div tag, like below - 我正在使用div标签的innerHTML属性,如下所示 -

var txt = document.getElementById("paidby").innerHTML;
document.getElementById("paidby").innerHTML=txt+ "<div class='row' style='padding:2px'><div class='col-sm-4'><input type='number' placeholder="+str+"></div></div>";

But I want to know if there is any other better way using angularJS or javascript to do the same so that if I need to remove one or all of the textfields later on, it can be done easily. 但我想知道是否还有其他更好的方法使用angularJS或javascript来做同样的事情,这样如果我以后需要删除一个或所有文本字段,它可以很容易地完成。 By removing means deleting and NOT hiding. 通过删除手段删除和不隐藏。

(becuase if I want to remove for example textfield 'two' now, I have no idea how I remove it) (因为如果我想删除例如textfield'two'现在,我不知道我是如何删除它的)

You don't want to manipulate the DOM within your controller. 您不希望在控制器中操作DOM。 Often times, there are better ways to do this within the framework that Angular provides. 通常,在Angular提供的框架内有更好的方法可以做到这一点。

You can do this by having another ng-repeat which loops over an array you declare within your controller. 您可以通过在控制器中声明的数组上循环另一个ng-repeat来实现此目的。 For example: 例如:

In your view: 在你看来:

<section id="paidby" ng-repeat="textfield in textfields">
  <div class='row' style='padding:2px'>
    <div class='col-sm-4'>
      <input type='number' placeholder="{{textField.str}}" ng-model="textField.value">
    </div>
  </div>
</section>

In your controller, within your button ng-click logic: 在您的控制器中,在按钮ng-click逻辑中:

// To add:
$scope.textFields.push({ str: someVariable, value: someValue });

// To remove:
var index = $scope.textFields.map(function(t) { return t.value; }).indexOf(someValue);
if (index !== -1) {
  $scope.textFields.splice(index, 1);
}

Try hiding the inputs to start with, then show them if the appropriate button is clicked: 尝试隐藏输入以开始,然后在单击相应按钮时显示它们:

 <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <div ng-app="" ng-init="array=['one','two','three','four','five']; show=[false,false,false,false,false]"> <button ng-repeat="item in array" ng-click="show[$index] = !show[$index]">{{item}}</button> <br> <input type="text" ng-repeat="item in array" placeholder="{{item}}" ng-if="show[$index]" /> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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