【发布时间】:2014-02-02 17:46:49
【问题描述】:
我有两个具有相同列表的 ng-repeat 的 div。但是当我从第一个 div 更改一个列表项的内容时,第二个 div 接收相同的值。我认为 ng-repeats 有孤立的范围?如何归档 ng-repeats 的隔离?
编辑: “在大多数情况下,指令和作用域交互但不会创建新的作用域实例。但是,某些指令,例如 ng-controller 和 ng-repeat,会创建新的子作用域并将子作用域附加到对应的 DOM 元素。” http://docs.angularjs.org/guide/scope
<div ng-controller="MyCtrl">
<button ng-click="newitem()">add item </button>
<div ng-repeat="item in list">
<input ng-model="item.name" placeholder="Name*">
<input ng-model="item.lastname" placeholder="Last name*">
<input ng-model="item.username" placeholder="Username(Email)*">
</div>
here is another div with ng-repeat of the same list. why do they share scope?
<br>
<div ng-repeat="item in list">
<input ng-model="item.name" placeholder="Name*">
<input ng-model="item.lastname" placeholder="Last name*">
<input ng-model="item.username" placeholder="Username(Email)*">
</div>
js:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.list = [];
$scope.newitem = function () {
$scope.list.push({name: "", lastname: "", username: ""});
}
}
【问题讨论】:
-
因为最终您在同一个控制器中使用相同的数据源,如果您想更改一个列表而不更改另一个列表,然后复制该列表?
-
但是 ng-repeat 根据 angularjs 创建了新的范围?我真的认为 ng-repeat 是从父级(控制器范围)继承的,然后对它所做的新范围进行了所有更改。
-
我确实知道实现目标的方法,但我仍然想要对此进行解释。我的解决方法是创建一个新的控制器实例。
标签: angularjs angularjs-ng-repeat