簡體   English   中英

如何在角度js中單擊按鈕添加和刪除文本字段

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

我在角度js中使用ng-repeat指令生成了按鈕。 現在我想在點擊該按鈕時在div標簽內生成一個文本字段。

示例按鈕 -

在此輸入圖像描述

點擊它添加示例文本字段 -

在此輸入圖像描述

我正在使用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>";

但我想知道是否還有其他更好的方法使用angularJS或javascript來做同樣的事情,這樣如果我以后需要刪除一個或所有文本字段,它可以很容易地完成。 通過刪除手段刪除和不隱藏。

(因為如果我想刪除例如textfield'two'現在,我不知道我是如何刪除它的)

您不希望在控制器中操作DOM。 通常,在Angular提供的框架內有更好的方法可以做到這一點。

您可以通過在控制器中聲明的數組上循環另一個ng-repeat來實現此目的。 例如:

在你看來:

<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>

在您的控制器中,在按鈕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);
}

嘗試隱藏輸入以開始,然后在單擊相應按鈕時顯示它們:

 <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