Ng-重复并创建新的子范围

时间:2014-09-22 14:21:51

标签: angularjs

我只是想了解一下 如果np-repeat在每次迭代中创建一个新的子作用域,那么为什么此代码在父作用域中而不是在子作用域中设置变量:



var app = angular.module('myApp', []);

        app.controller('WorldCtrl', function($scope) {
            $scope.population = 7000;
            $scope.countries = [
                {name: 'France', population: 63.1},
                {name: 'United Kingdom', population: 61.8},
            ];
        });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='WorldCtrl'>
<li ng-repeat="country in countries">
        <span ng-init="country.name='Egypt'"></span>
        {{country.name}} has population of {{country.population}}
</li>
  
 <hr>
    World's population: {{population}} millions {{countries}}
</div>
&#13;
&#13;
&#13;
预期产出:

 Egypt has population of 63.1
 Egypt has population of 61.8
World's population: 7000 millions [{"name":"France","population":63.1},{"name":"United Kingdom","population":61.8}]

2 个答案:

答案 0 :(得分:1)

答案是因为作为对象,您传递的是引用而不是模型的副本。 ng-repeat正在创建一个变量country,它是数组countries的当前迭代对象的引用,因此您正在改变引用对象的属性,而不是复制。

答案 1 :(得分:1)

ng-repeat确实创建了自己的范围,它掩盖了父范围中定义的变量。也就是说,如果父作用域具有名为country的属性,您将无法在ng-repeat模板中访问它。

但是,子作用域中创建的country属性是由父作用域中的属性引用组成的。这就是JavaScript原型继承的工作原理。

你可以通过覆盖整个country属性而不是使用原型链来解决这个问题。

&#13;
&#13;
var app = angular.module('myApp', []);

        app.controller('WorldCtrl', function($scope) {
            $scope.population = 7000;
            $scope.countries = [
                {name: 'France', population: 63.1},
                {name: 'United Kingdom', population: 61.8},
            ];
        });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='WorldCtrl'>
<li ng-repeat="country in countries">
        <span ng-init="country = {name: 'Egypt', population: country.population}"></span>
        {{country.name}} has population of {{country.population}}
</li>
  
 <hr>
    World's population: {{population}} millions {{countries}}
</div>
&#13;
&#13;
&#13;