Angularjs动态添加和删除输入

时间:2015-08-14 17:40:17

标签: angularjs


我在jsfiddle上的代码。

HTML

<div ng-controller="MyCtrl">
  <input>
  <button ng-click='add()'>Add</button>
  <br/>
  <b>Items Added Below</b>
  <div ng-repeat='item in items'>
    <input ng-model='item' id='item-{{$index}}' class='input-{{$index}}'/>
    <button ng-click='del($index)'>DEL</button>
  </div>
</div>

角度控制器

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
  $scope.items = [];
  $scope.newitem = '';
  $scope.add = function(){
    if ($scope.items.length < 4) {
      $scope.items.push($scope.newitem);
    }
  }
  $scope.del = function(i){
    $scope.items.splice(i,1);
  }
}

我尝试通过ng-click动态添加输入并删除特定但总是删除最后一个输入..
我认为它是因为它们在项目数组中没有区别。
我怎么解决这个问题?

3 个答案:

答案 0 :(得分:3)

这有两个部分:

  1. 您没有绑定第一个输入(在添加旁边)。这意味着您只是在数组中添加''。据我所知,angularjs按键跟踪,默认情况下不是索引。这导致我进入第2部分。
  2. 您使用的是旧的AngularJS版本,根据docs,它无法选择“{expr}跟踪$ index”。请查看1.4.4 docs了解相关信息。
  3. 所以我可能会使用最新稳定的AngularJS,并确保你的第一个输入绑定到$ newitem。

答案 1 :(得分:2)

看看以下小提琴:

fiddle :: http://jsfiddle.net/4zt4ynzL/

问题是你每次都在推送数组中的空字符串。

正如我在上面提到的那样,我在每次点击添加按钮时都推了一个新值。

P.S。 :你这样做是正确的:)

答案 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);
    }
}
相关问题