2015-08-14 87 views
3


我的代碼在jsfiddle
Angularjs動態添加和刪除輸入

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); 
    } 
} 

我嘗試動態添加輸入伍單擊並刪除特定卻始終刪除最後輸入..
我想它因爲它們沒有區分項目數組。
我該如何解決這個問題?

+0

我略作修改小提琴表明你是不正確的。如果我將值添加到「newitem」以便我可以看到我正在刪除的內容,它會正確刪除我告訴它刪除的項目。 http://jsfiddle.net/9j34dnpo/ –

+0

你爲什麼使用angular 1.0.1? – Ronnie

+0

仍然不刪除特定的輸入,但總是最後一個:/ @Ronnie在我的項目上我使用更新的版本:)你認爲問題是angularjs的版本? – m1l05z

回答

1

你的代碼工作正常,只要你想。

只是一個錯誤,你沒有添加ng模型輸入newitem。

Look JsFiddle

<div ng-app="myApp"> 
    <div ng-controller="MyCtrl"> 
    <input ng-model="newitem"> 
    <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> 
</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); 
    } 
} 
+0

對不起,但你的代碼不能正常工作:/ – m1l05z

+0

其代碼我告訴它的問題.. :) 你究竟想要什麼..? –

+0

刪除特定的輸入..在你的jsfiddle我只能添加一個輸入,然後添加按鈕不工作.. – m1l05z

3

有兩個部分是:

  1. 你是不是綁定你的第一個輸入(旁邊添加)。這意味着你只是將「'添加到數組中。據我所知,angularjs通過鍵跟蹤,而不是默認的索引。這導致我到第2部分。
  2. 您正在使用一箇舊的AngularJS版本,它根據docs沒有選項「{expr} track by $ index」。有關此信息,請參閱1.4.4 docs

所以我可能會使用最新的穩定的AngularJS,並確保您的第一個輸入綁定到$ newitem。

+0

真的很感謝:) – m1l05z

2

看一看下面的小提琴:

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

的問題是,你正在推動在陣列中每一次空字符串。

正如我在上面的小提琴中所展示的,每增加一次按鈕,我都會推出一個新的值。

P.S. :你做的一切都是正確的:)

1

在簡單的方法,你可以這樣做:

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); 
    } 
}