在 ng-repeat 中修改 Angular 范围内的对象 [英] Modifying objects within Angular Scope inside ng-repeat
问题描述
我正在使用 ng-repeat 在 HTML 中创建一个表单,以从范围内的对象生成表单元素.我还使用该对象生成 ng-repeat 之外的其他元素.
HTML 中的简化示例如下所示:
<div ng-controller="Ctrl"><div class="block1"><form ng-repeat="(key, value) in test"><label>{{key}}</label><input ng-model="value"/><p>{{value}}</p></表单><div class="block2"><p>{{test.a}}</p><p>{{test.b}}</p>
在 JS 中:
angular.module('App', []);功能Ctrl($范围){$scope.test = {a:"abc",b:定义"}}
在本例中,block2 中的文本被设置为test.a
和test.b
的初始值.循环内的输入值和 值也设置为初始值.
当我修改输入中的值时,ng-repeat 块内的 <p>
值会正确更新,但 <p>
标记在block2 更新失败.
为什么会出现这种行为?ng-repeat 是否创建了自己的隔离范围?如果是这样,我如何才能更新控制器级别的范围?另外,有人可以解释这种行为背后的想法以及它提供的任何优势吗?
ng-repeat
为每个重复项创建一个子作用域.因此,您正在尝试将原语传递给子作用域,而该子作用域不会创建对父级的引用.但是,当您传递对象时,您传递的是原始对象引用.
来自 Angular 之父之一的口中:
<块引用>在 ng-model 中总是有一个点
这是一个关于 Angular 最佳实践的精彩视频,由 Angular 创建者提供(2012/12/11).转到第 31 分钟,详细了解这种确切情况
将数据修改为对象数组:
$scope.test = [{ val:"abc",key:'a'}, {val:"def",key:'b'} ]
然后在中继器中:
I'm creating a form in HTML using ng-repeat to generate the form elements from an object in the scope. I also use that object to generate other elements outside of the ng-repeat.
A simplified example looks like this in HTML:
<div ng-app="App">
<div ng-controller="Ctrl">
<div class="block1">
<form ng-repeat="(key, value) in test">
<label>{{key}}</label>
<input ng-model="value" />
<p>{{value}}</p>
</form>
</div>
<div class="block2">
<p>
{{test.a}}
</p>
<p>
{{test.b}}
</p>
</div>
</div>
</div>
and this in JS:
angular.module('App', []);
function Ctrl($scope) {
$scope.test = {
a:"abc",
b:"def"
}
}
In this example, the text in block2 is set to the initial values of test.a
and test.b
. The input values and <p>
values inside of the loop are also set to the initial value.
When I modify the values within the inputs, the <p>
values inside of the ng-repeat block update correctly, but the <p>
tags in block2 fail to update.
Why is this the behavior? Does ng-repeat create its own isolated scope? If so how can I get the controller level scope to update? Also, could somebody explain the thinking behind this behavior and any advantages it provides?
ng-repeat
creates a child scope for each repeated item. As a result you are trying to pass a primitive to child scope which won't create a reference to parent. When you pass objects however, you pass the original object reference.
From the mouth of one of the fathers of Angular:
Always have a dot in ng-model
This is a great video regarding Angular Best Practices given by Angular creator (2012/12/11). Go to minute 31 for well explained detail of this exact situation
Modify data to array of objects:
$scope.test = [{ val:"abc",key:'a'}, {val:"def",key:'b'} ]
Then in repeater:
<form ng-repeat="item in test">
<label>{{item.key}}</label>
<input ng-model="item.val" />
<p>{{item.val}}</p>
</form>
这篇关于在 ng-repeat 中修改 Angular 范围内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!