2015-11-18 26 views
0

我需要從使用html輸入鍵入和提交的值構建ng-repeat列表。它可以工作,我可以使用ng-repeat從輸入中返回項目,但是在編輯下一個項目的輸入時,輸入值仍然綁定到ng-repeat中的值,然後更改該值而不是添加全新的。我確信我錯過了一件簡單的事情,但暫時陷入困境。如何添加項目ng-repeat列表和停止列表項目正在通過數據綁定更改

如何在每次ng-click時添加未綁定到輸入的新項目?

HTML:

<div ng-controller="MyCtrl"> 
Hello, {{name}}! 
<br/> 
<input ng-model='newitem1' /> 
<input ng-model='newitem2' /> 
<input ng-model='newitem3' /> 
<button ng-click='add()'>Add</button> 

<br/> 
<b>Items Added Below</b> 
<div select-last ng-repeat='item in items'> 
    <div ng-model='item' id='item-{{$index}}' class='input-{{$index}}'>{{newitem1}} {{newitem2}} {{newitem3}}</div> 
</div> 

的Javascript:

var myApp = angular.module('myApp',[]); 

myApp.directive('selectLast', function() { 
    return function (scope, element, attrs) { 

     if (scope.$last=== true) { 
      console.log("the last element is here"); 
     } 
    } 
}); 
function MyCtrl($scope) { 
    $scope.name = 'Please try entering something and click Add button'; 
    $scope.items = []; 
    $scope.newitem1 = ''; 
    $scope.newitem2 = ''; 
    $scope.newitem3 = ''; 

    $scope.add = function(){ 
     $scope.items.push($scope.newitem1,$scope.newitem2,$scope.newitem3); 
    } 

} 

回答

1

你可以克隆使用angular.copy()的項目所以它是數據的副本,但不是直接引用它。

這將允許您不斷添加新項目。

function MyCtrl($scope) { 
    $scope.name = 'Please try entering something and click Add button'; 
    $scope.items = []; 
    $scope.newitem1 = ''; 
    $scope.newitem2 = ''; 
    $scope.newitem3 = ''; 

    $scope.add = function(){ 
     var item1 = angular.copy($scope.newitem1), 
      item2 = angular.copy($scope.newitem2), 
      item3 = angular.copy($scope.newitem3); 
     $scope.items.push(item1, item2, item3); 
    } 
} 
0

我意識到我使用輸入模型來表達我的表情。

{{newitem1}} 

而不是

{{item.newitem1}} 

固定