使用ng repeat添加多个视图实例时的范围界定问题
Scoping issue when adding multiple instances of views using ng-repeat
我在使用AngularJS的ng repeat功能时遇到了范围界定问题。
请看plnkr
我有一个对象数组"boxCollection"和一个项目列表"itemCollection",它们显示在下拉列表中。
$scope.boxCollection = [];
$scope.itemCollection =
[
{name: 'item1'},
{name: 'item2'},
{name: 'item3'}
];
现在我有了的观点
<script type="text/ng-template" id="addBox.html">
<div class="box-controls">
<span class="glyphicon glyphicon-plus pull-left" ng-click="addBox()"></span>
<span class="glyphicon glyphicon-minus pull-left" ng-class="{disable_div:boxCollection.length < 2} " ng-click="removeBox($index)"></span>
</div>
<div class="box-container">
<div class="box-details">
<div class="boxItem">
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-3">Item</label>
<div class="col-md-8">
<select class="form-control" ng-options="item.name for item in itemCollection" ng-model="boxCollection[$index].item" ng-disabled="false">
<option value=""> None </option>
</select>
</div>
</div>
<div class=" form-group ">
<label class="control-label col-md-3">Item Desc</label>
<div class="col-md-8">
<input type="text " class="form-control " ng-model="boxCollection[$index].item.desc ">
</div>
</div>
</form>
</div>
</div>
<div class="clearfix "></div>
</div>
</script>
视图被包装在一个带有id的脚本标记中,并使用ng repeat进行调用。
我有一个函数可以在视图"addBox()"中添加一个box元素。它在"boxCollection"数组中生成一个条目,在"boxTmplList"数组中产生另一个条目boxTmplList负责显示视图。
现在,如果您从box1的下拉列表中选择"item1",并在输入字段中添加值,则使用"+"按钮在视图中添加另一个框,然后在另一个实例中再次选择"item1"。它在输入字段2中显示输入字段1的值。
在此处输入图像描述
在进一步的分析中,我发现Angular使用相同的$hashkey跟踪具有类似"item"名称的对象。
我正在使用一种解决方法,将另一个属性添加到对象"boxCollection[$index].itemDesc"而不是"boxCollection[%index].item.desc",然后稍后使用另一个函数修改对象,但我觉得这不是最有效的方法。
如对此有任何见解,我们将不胜感激。
您需要将ng-model="boxCollection[$index].item"
更改为ng-model="boxCollection[$index].item.name"
,如-
<select class="form-control" ng-options="item.name for item in itemCollection" ng-model="boxCollection[$index].item.name" ng-disabled="false">
工作程序
将ng-model="boxCollection[$index].item.desc"
更改为ng-model="itemCollection[$index].name"
。
<div class=" form-group ">
<label class="control-label col-md-3">Item Desc</label>
<div class="col-md-8">
<input type="text " class="form-control " ng-model="itemCollection[$index].name">
</div>
</div>
- setInterval游戏循环的范围问题
- firefox中的Javascript事件范围问题
- jQuery“this”范围问题
- 可以't在quizz页面范围问题上用最终分数更新变量
- JavaScript 函数变量范围问题
- 奇怪的可变范围问题
- AngularJS中的范围问题
- 如何在 JavaScript for D3.js 中解决这样的范围问题
- 我可以设置这个吗'某事'在该服务中动态创建的嵌套对象中的服务?(可能是范围问题)
- Angular.js的多个rest调用范围问题
- Angular-$http范围问题
- setTimeout范围问题
- NodeJS回调范围问题
- javascript函数的可变范围问题
- 可能存在Javascript范围问题
- 函数之间的Javascript变量范围问题
- 单击视图时的应用器范围问题
- 全球不断改变价值.可能通过引用或范围问题传递?帮助!链接中的详细示例
- 挖空 - 单击绑定到对象函数 - 范围问题
- Angular 在 http 请求后不更新页面(范围问题?