2016-08-03 25 views
0

使用Angular("angular": "~1.4.3"),我有一個ng-repeated列表,我想用項目名稱添加項目並使用文本框內聯編輯項目名稱。當我添加多個新項目的陣列發生帶內聯文本編輯的ng-repeat影響其他項目

enter image description here

的問題。當我在一個文本中更改文本時,會影響另一個文本。我輸入Hello行項目1,並被推到H項目2和1,其餘:

enter image description here

這是我如何添加新對象(使用unshift用它強制頂部列表):

$scope.addObj = function() { 
     $scope.new_categories.unshift({ 
      category : '', 
      other data... 
     }); 
    }; 

HTML:

<tr ng-repeat="c in new_categories | orderBy:sortType:sortReverse | filter:searchCategories track by $index" class="newly-added"> 
    <td class="third-width-input"> 
     <input type="text" name="category" placeholder="New Category" class="form-control" ng-blur="" ng-model="c.category"> 
    </td> 
</tr> 

編輯:建議,使用$index建議在答案中會改變你的對象的結構。

PLUNKER

綁定模型,我原來有,c.category_name認爲:

{ 
    //This is a Category Object 
    category_name: 'some string', 
    other data on the category obj 
} 

但使用c.category_name[$index]改變它:

{ 
    //This is a Category Object 
    category_name: Object { 0 : 'some string' }, 
    other data on the category obj 
} 

HTML:

<tr ng-repeat="c in new_categories | orderBy:sortType:sortReverse | filter:searchCategories track by $index" class="newly-added"> 
    <td class="third-width-input"> 
     <input type="text" name="category" placeholder="New Category" class="form-control" ng-blur="" ng-model="c.category[$index]"> 
    </td> 
    <button ng-class="{ 'button-error' : !c.category[$index].length }" type="button" ng-click="saveAddedCategory(c); c.saving = true; c.updated = false" class="buttons green inline" ng-disabled="!c.category[$index].length"> 
     Save 
    </button> 
</tr> 

JS:

$scope.saveAddedCategory = function(category) { 
     console.log('cat', category); 
    }; 

CONSOLE.LOG生產:

enter image description here

+0

請加plunker或JS小提琴? – SrinivasAppQube

+0

什麼叫addObj? – garethb

回答

2

您使用的是相同的ngModel爲您的所有投入。你應該將其更改爲:

<input type="text" ng-model="c.category[$index]" name="category" placeholder="New Category" class="form-control" ng-blur=""> 

所以你可以有這樣的:

<tr ng-repeat="c in new_categories | orderBy:sortType:sortReverse | filter:searchCategories track by $index" class="newly-added"> 
    <td class="third-width-input"> 
     <input type="text" ng-model="c.category[$index]" name="category" placeholder="New Category" class="form-control" ng-blur=""> 
    </td> 
</tr> 
+1

我以爲默認情況下,對象屬性上的'ng-model'採用了不同的索引。有用的信息 – Growler

+0

請參閱上面的編輯。嘗試保存類別對象時出現奇怪的更改 – Growler

+0

我看不到任何*怪異的東西。這是預期的行爲。你的'ngModel'應該是這樣的..'category [0] ='dddd'.. category [1] ='aaa''等等.. – developer033

相關問題