在angularjs中以动态方式添加和删除文本字段

时间:2016-11-03 13:44:12

标签: angularjs

我想通过添加按钮单击添加和删除angularjs中的文本字段。在文本字段的右侧,添加了应该有一个删除选项。当我点击删除文本字段时应该删除。

3 个答案:

答案 0 :(得分:3)

我会使用 ng-repeat 来解决这个问题。看看这个例子: 修改更新了代码:

angular.module("module",[])
.controller("ctrl",function($scope){
  $scope.inputList = [];
  $scope.add = function(){
    $scope.inputList.push({content:""});
  };
  $scope.remove = function(input){
    var idx = $scope.inputList.indexOf(input);
    $scope.inputList.splice(idx,1)
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="module" ng-controller="ctrl">
  <div ng-repeat="input in inputList">
    <input type="text" ng-model="input.content">
    <input type="button" ng-click="remove(input)" value="remove">
  </div>
  <input type="button" ng-click="add()" value="add">
</div>

答案 1 :(得分:0)

您可以使用ng-repeat来实现此功能。 每次用户按下“添加”按钮时,您必须在$ scope对象的数组中添加一个对象,并在用户按下 - 按钮时删除该对象。

这是代码示例。

<span ng-click="addTextBox()"> + </span>
<div ng-repeat="textBox in textBoxes">
    <input type='text' />
    <span ng-click="removeTextBox(textBox.id)"> - </span>
</div>

控制器就像这样

$scope.textBoxes = [];
$scope.addTextBox = function() {
    $scope.textBoxes.push({id: $scope.textBoxes.length +1});
}
$scope.removeTextBox = function(id){
    var indexToRemove;
    for(i = 0; i < $scope.textBoxes.length; i++){
        if($scope.textBoxes[i].id === id){
            indexToRemove = i;
        }
        $scope.textBoxes.splice(indexToRemove, 1);
    }
}

答案 2 :(得分:0)

您可以使用这种简单的方式:

<强> HTML

<span ng-repeat="hobby in hobbies track by $index">
    <div class="form-group">
        <input type='text' ng-model='hobbies[$index]' class="form-control pull-right"/>
        <button ng-click = "addHobby()" ng-show="$last">+</button>
        <button ng-click = "removeHobby($index)" ng-show="hobbies.length > 1">-</button>
    </div>
</span>

角度控制器

$scope.hobbies = [''];

$scope.addHobby = function() {
    $scope.hobbies.push('');
}

$scope.removeHobby = function(index) {
    if(index >= 0){
        $scope.hobbies.splice(index, 1);
    }
}