2017-04-12 16 views
0

我在Angular 1.x中使用ng-repeat,並且我嘗試創建每個迭代唯一的ID/class/ng-model。如何在ng-repeat中使用ng-model

<input type="text" id="url-placeholder" placeholder="Companion URL" class="creative-url-box" ng-model="newCreative.companionUrl"> 

這一切都是ng-repeat下,當我要創建新的對象,創造了我同一個對象所有的時間。

我試圖添加{{$id}} ID和類,但出了問題。 那麼我該怎麼做?

感謝

回答

1

當我要創建新的對象,創造了我同一個對象所有的時間?

ng-model="newCreative.companionUrl"> 

在每次迭代中使用的是相同的model .Thats爲什麼你得到相同的值。

使用ng-repeat它提供$index在每次迭代中具有不同的值。

我們可以用它來創建新的模態實例。現在

<div ng-repeat="oneRec in arrRec"> 
<input type="text" id="url-placeholder" ng-model="newCreative[$index].companionUrl"> 
</div> 

,你有newCreative訪問陣列使用它。它的索引將創建新的對象

+0

偉大的,謝謝! :) –

+0

:D dpnt忘記upvote:P –

0

試試這個

<!DOCTYPE html> 
 
<html> 
 
<head> 
 

 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script> 
 
    <script type="text/javascript"> 
 

 

 
    angular.module("app",[]) 
 
    .controller("ctrl",function($scope){ 
 

 
     $scope.urlData = [{ 
 
     id:1, 
 
     url:'google.com' 
 
     },{ 
 
     id:2, 
 
     url:'stackoverflow.com' 
 
     }] 
 

 

 

 
    }); 
 

 
    </script> 
 
</head> 
 
<body ng-app="app" ng-controller="ctrl"> 
 
<div ng-repeat="data in urlData track by $index"> 
 
    {{data.id}}, 
 
    <input type="text" ng-model="data.url"> 
 
</div> 
 
</body> 
 
</html>

0

使用$indexng-repeat動態裏面,象下面這樣:

<input type="text" id="url-placeholder" placeholder="Companion URL" class="creative-url-box" ng-model="newCreative.companionUrl{{$index}}"> 

但是,推薦的方法是使用嘗試使用您的迭代器newCreativecompanionUrl屬性,它將對每個集合項都是唯一的。

例如像:

<Div ng-repeat = "newCreative in newCreativeCollection track by $index"> 
    <input type="text" id="url-placeholder" placeholder="Companion URL" class="creative-url-box" ng-model="newCreative.companionUrl"> 
</Div> 

在您newCreativeCollection,應該是這樣的:

$scope.newCreativeCollection = [{ 
     companionUrl : '', 
     //other properties 
     }, 
     .. othet items 
    ]