2014-09-22 49 views
0

我只是想了解
如果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>

預期輸出:

 
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}] 
+0

我很困惑;你期望會發生什麼? – 2014-09-22 14:27:56

+0

@ExplosionPills我編輯了這個問題,請看一看 – 2014-09-22 14:31:02

+1

它在父範圍中設置'country.name',因爲'coutry'是從JS原型鏈中讀取的,它在這個對象中找不到,所以從父對象,然後設置'name'。 – 2014-09-22 14:36:37

回答

1

答案是,因爲作爲一個對象,你逝去的引用,而不是模型的副本。 ng-repeat會創建一個變量country,它是數組countries的當前迭代對象的引用,因此您正在修改引用對象的屬性,而不是副本。

+0

啊啊,我怎麼錯過了!如果是:$ scope.countries = [ '法國', '英國' ];那麼它會像我想象的那樣工作。謝謝。 – 2014-09-22 14:40:02

1

ng-repeat確實創建了自己的作用域,它使父範圍中定義的變量超出陰影。也就是說,如果父範圍有一個名爲country的屬性,那麼您將無法在ng-repeat模板中訪問它。

但是,在子作用域中創建的country屬性由對父作用域中的屬性的引用組成。這就是JavaScript原型繼承的工作原理。

您可以通過覆蓋整個country屬性而不是使用原型鏈來解決此問題。

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', population: country.population}"></span> 
 
     {{country.name}} has population of {{country.population}} 
 
</li> 
 
    
 
<hr> 
 
    World's population: {{population}} millions {{countries}} 
 
</div>

+0

謝謝你,我剛剛有一個阿哈哈的時刻 – 2014-09-22 14:43:19