[英]AngularJS ng-repeat input
我正在嘗試使用Angular js進行評論功能。 問題是,當我要為帖子寫評論時,文本也在其他輸入元素(評論)中書寫。 我在一個輸入中寫了一個文本,但在所有輸入中都寫了它
因此,例如此代碼也發生了同樣的情況
<div class="comments" ng-repeat="articles in [1,2,[4,5,6]]">
<div ng-repeat="comments in articles">
<div>
<input type="text" ng-model="$parent.new">
</div>
</div>
如果我使用new而不是$ parent.new,我將無法定義,但是當我使用$ parent.new並在一個輸入中寫入時,它也會在其他輸入中寫入。
問題是您要將所有輸入分配給同一模型,因此您的輸入都與同一個對象同步。
您需要將每個輸入分配給不同的模型。 我猜想您需要這些模型是動態的,因此您應該使用數組作為模型,並通過$index
跟蹤ng-repeat
,如下所示:
<div ng-repeat="comments in articles track by $index">
<div>
<input type="text" ng-model="arr[$index]">
<span ng-if="arr[$index]">
{{arr[$index]}}
</span>
</div>
</div>
現在,在您的控制器中,您可以像這樣初始化空的arr
:
$scope.arr = [];
現在,您的輸入將與$scope.arr
同步,具體取決於它們所在的索引。
試試這個jsfiddle作為例子。
這是因為您為所有inputs
都提供了相同的model
( ng-model="$parent.new"
),為避免此問題,應該為每個輸入元素分配不同的model
。 就像是
<div class="comments" ng-repeat="articles in [1,2,[4,5,6]]">
<div ng-repeat="comments in articles">
<div>
<input type="text" ng-model="comments">
</div>
</div>
將輸入的ng-model更改為
<input type="text" ng-model="comments.comment">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.