NG-重复内角范围内修改对象 [英] Modifying objects within Angular Scope inside ng-repeat

查看:135
本文介绍了NG-重复内角范围内修改对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML中使用NG重复生成从范围内的对象表单元素创建表单。我也使用该对象生成NG重复之外的其他元素。

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.

一个简单的例子看起来像这样在HTML:

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>

而这JS:

angular.module('App', []);

function Ctrl($scope) {
    $scope.test = {
        a:"abc",
        b:"def"
    }
}

在这个例子中,在块2的文本设置为 test.a test.b 。输入值和&LT; P&GT; 环路内的值也设置为初始值

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.

当我修改输入,&LT内的值; P&GT;正确NG重复块更新内部值,但&LT ; p&GT; 在块2标签无法更新

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.

为什么会出现这种现象?不NG-重复创建自己的隔离范围是什么?如果是的话我怎么能得到控制器级别范围更新?另外,可能有人解释这种行为背后的思维和提供?

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?

的jsfiddle显示问题

推荐答案

NG-重复为每个项目重复一个子范围。因此,您正在试图通过一个原始到不会产生父参考子范围。然而,当你传递对象,你传递原始对象引用。

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.

从角的创始人之一的嘴:

始终在NG-model的点

这是对角的最佳实践 通过角创作者给出(一个伟大的视频2012年12月11日)。转到井分31解释这一确切的情况详细

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

修改数据对象的数组:

$scope.test = [{ val:"abc",key:'a'}, {val:"def",key:'b'} ]

然后在中继器:

<form ng-repeat="item in test">
  <label>{{item.key}}</label>
  <input ng-model="item.val" />
  <p>{{item.val}}</p>
</form>

<大骨节病> 演示

这篇关于NG-重复内角范围内修改对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆