2016-03-26 34 views
2

這是我的代碼如何在ng-repeat中爲AngularJs中的mutilpe文本字段實現ng模型?

function Ctrl($scope) { 
 
    $scope.data = []; 
 

 
    $scope.data = [{ 
 
    "label": "name", 
 
    "type": "string" 
 
    }, { 
 
    "label": "email", 
 
    "type": "string" 
 
    }]; 
 
    $scope.addFields = function() { 
 
    var count = 0; 
 
    angular.forEach($scope.data, function(obj) { 
 
     if (count == 2) { 
 
     return true; 
 
     } 
 
     $scope.data.push(obj); 
 
     count = count + 1; 
 
    }); 
 
    }; 
 
    $scope.save = function() { 
 
    console.log($scope.data); 
 
    }; 
 
}
<div ng-app> 
 
    <div ng-controller="Ctrl"> 
 
    <input type="button" value="add" ng-click="addFields()" /> 
 
    <div ng-repeat="eachItem in data"> 
 
     <label>{{eachItem.label}}</label> 
 
     <input type="text" ng-model="eachItem.value" /> 
 
    </div> 
 
    <input type="button" value="save" ng-click="save()" /> 
 
    </div> 
 
</div>

這是我的jsfiddle http://jsfiddle.net/0c5p38dt/5/ 在上面的代碼我有多個對象的陣列,這些目的從服務動態獲取。當我再次單擊添加按鈕時,相同的對象將推到相同的數組。我在ng-repeat內部使用ng-model作爲textfield。但是當我輸入的數據也會影響其他文本域。所以如何區分數組中多個相同對象的ng模型值。

+0

如你所說,同樣的對象推到相同的陣列。輸入數據時,您正在修改相同的對象,因此綁定到相同ng模型的所有字段也會被更改。在addField函數中,如果克隆該對象,即angular.copy(obj)。在將其推入陣列之前,您應該看到區別。但我不確定這是否是你想要的。 – sdfacre

回答

3

您的addFields()函數不添加具有自己對象的字段。它正在創建指向現有對象的新字段。

本質上,當調用addFields()時,它會說「添加兩個指向與前兩個字段相同的對象的新字段」。這就是爲什麼他們都共享相同的模型。

的解決方案是真正創建一個新的對象,它是原來在addFields()功能,像這樣的克隆:

$scope.addFields = function() { 
    var count=0; 
    angular.forEach($scope.data,function(obj){ 
     if(count==2){ 
      return true; 
     } 

     // Create a new object with the same properties as the original 
     var newObj = {'label':obj.label, 'type':obj.type} 
     $scope.data.push(newObj); 
     count=count+1; 
    }); 
}; 

我修改您的jsfiddle:http://jsfiddle.net/nhupL4gs/

+0

謝謝你@Richard Pressler。我想要輸出的是你給出的確切代碼。非常感謝你 –

相關問題