簡體   English   中英

當子控制器修改父范圍變量時,父范圍變量不會在視圖中更新

[英]Parent scope variables don't update in the view when child controllers modify them

可以在這里找到關於這個問題的jsFiddle: http : //jsfiddle.net/Hsw9F/1/

JavaScriptjsFiddle中提供了console.log調試信息)

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

function ParentController($scope) {
 $scope.parentCounter = 5;
}

function ChildController($scope) {
  $scope.childCounter = $scope.parentCounter;
  $scope.increaseCounters = function() {
    ++$scope.parentCounter;
    ++$scope.childCounter;
  };
}

在上面的示例中,我在父控制器和子控制器中分別有一個計數器,分別命名為parentCounterchildCounter 我還在子控制器中提供了一個名為increaseCounters()的函數,該函數將兩個計數器都增加一個。

這兩個計數器都顯示在頁面上:

<div ng-app="StackOverflow">
  <div ng-controller="ParentController">

    Parent Counter: {{parentCounter}}<br />

    <div ng-controller="ChildController">
      Child Counter: {{childCounter}}<br />
      <a href="javascript:void(0)"
         ng-click="increaseCounters()">Increase Counters</a>
    </div><!-- END ChildController -->

  </div><!-- END ParentController -->
</div><!-- END StackOverflow app -->

問題是AngularJS似乎不更新頁面上的{{parentCounter}} ,而僅在調用增加計數器功能時更新{{childCounter}} 有什么我忽略的嗎?

++$scope.parentCounter; 創建一個名稱為parentCounter的子范圍屬性,該屬性隱藏/陰影相同名稱的父范圍屬性。

添加console.log($scope); 到您的gainCounters()函數中查看它。

一種解決方法: ++$scope.$parent.parentCounter;

您遇到的問題與JavaScript原型繼承的工作方式有關。 我建議閱讀AngularJS中范圍原型/原型繼承的細微差別? -它有一些漂亮的圖片,解釋了在子范圍內創建基元時會發生什么。

因為子控制器獲取父計數器值的副本。 如果要增加父控制器的計數器值,則需要在父控制器上執行一個函數:

function ParentController($scope) {
 $scope.parentCounter = 5;

  $scope.increaseParent = function() {
     ++$scope.parentCounter;
  };
}

function ChildController($scope) {
  $scope.childCounter = $scope.parentCounter;
  $scope.increaseCounters = function() {
    console.log('-------------------------------------');
    console.log('parent before: ' + $scope.parentCounter);
    console.log('child before: ' + $scope.childCounter);
    $scope.increaseParent();
    ++$scope.childCounter;
    console.log('parent after: ' + $scope.parentCounter);
    console.log('child after: ' + $scope.childCounter);
  };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM