Angularjs rootScope注射液没有像预期的那样传播

时间:2015-03-24 19:57:53

标签: angularjs

我正在尝试更改$ rootScope变量的值,并让具有更新值的各种控制器可以访问该变量。但是,由于某些原因,$ rootScope中的更改值似乎未被任何通过$ rootScope访问它的控制器检测到。

在这个例子中,为什么“child”不反映改变的值?

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.15/angular.js" data-semver="1.2.15"></script>
  <script type="text/javascript">
    angular.module('myApp', [])
      .run(function($rootScope) {
        $rootScope.current = 'a';
      })
      .controller('ParentCtrl', ['$scope', '$rootScope',
        function($scope, $rootScope) {
          $scope.child = $rootScope.current;
        }
      ])
  </script>
</head>

<body ng-app="myApp">
  <div>
    <p>Value of "current": {{ current }}</p>
    <button ng-click="$root.current = 'b'">Change value to 'b'</button>
    <div ng-controller="ParentCtrl">
      Value of "current" (within ParentCtrl): {{ current }}
      <br>Value of "child" (via ParentCtrl injection of rootscope): {{ child }}
    </div>
  </div>
</body>

</html>

这是我的plunker。提前谢谢!

2 个答案:

答案 0 :(得分:2)

您必须注意rootScope变量,如下所示。

 $scope.$watch(function() {
            return $rootScope.current;
          }, function() {
              $scope.child = $rootScope.current;
            }, 
          true);

这是工作plunker。您可以阅读有关$ watch here

的更多信息

答案 1 :(得分:0)

这种方式应该有效,请检查Angularjs范围doc以便更好地理解

https://docs.angularjs.org/guide/scope

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
  document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.15/angular.js" data-semver="1.2.15"></script>
<script type="text/javascript">
angular.module('myApp', [])
  .run(function($rootScope) {
    $rootScope.current = 'a';
  })
  .controller('ParentCtrl', ['$scope', '$rootScope',
    function($scope, $rootScope) {
      $scope.root = $rootScope;
    }
  ])
 </script>
 </head>

<body ng-app="myApp">
  <div>
  <p>Value of "current": {{ current }}</p>
  <button ng-click="$root.current = 'b'">Change value to 'b'</button>
  <div ng-controller="ParentCtrl">
  Value of "current" (within ParentCtrl): {{ current }}
  <br>Value of "child" (via ParentCtrl injection of rootscope): {{ root.current }}
  </div>
 </div>
  </body>
 </html>