简体   繁体   English

在Controller中访问$ rootScope方法

[英]Accessing $rootScope methods in Controller

In this ng-book JSBin , does $scope.$watch() resolves to $rootScope.$watch() due to prototypal inheritance. 此ng书JSBin中 ,由于原型继承, $scope.$watch()解析为$rootScope.$watch()

Can we inject $rootScope explicitly inside the controller so that $scope would be same as $rootScope inside the controller, without going through prototypal inheritance? 我们是否可以在控制器内部显式注入$rootScope ,以便$scope与控制器内部的$rootScope相同,而无需进行原型继承?

Replicating code here for reference: 在此处复制代码以供参考:

    // open this example and type person.name into the test field
    angular.module('myApp', [])
    .controller('MyController',
    ['$scope', '$parse', function($scope, $parse) {

      $scope.person = {
        name: "Ari Lerner"
      };

      $scope.$watch('expr', function(newVal, oldVal, scope) {
        if (newVal !== oldVal) {
          // Let's set up our parseFun with the expression
          var parseFun = $parse(newVal);
          // Get the value of the parsed expression, set it on the scope for output
          scope.parsedExpr = parseFun(scope);
        }
      });
    }]);

Just inject it the same way as $scope or $parse , anything defined on $rootScope will be then accessible inside your controller. 只需以与$scope$parse相同的方式注入它,即可在控制器内部访问$ rootScope上定义的任何内容。

app.controller('MyController', ['$scope', '$parse', '$rootScope', 
   function($scope, $parse, $rootScope) {

      $rootScope.foo();

      console.log($rootScope.bar);
   }
]);

etc. 等等

If you intend to use the rootScope so badly, it has a provider just as scope does. 如果您打算如此严重地使用rootScope ,则它与scope一样具有提供程序。 Including '$rootScope' into your controller as you do with the '$scope' does the trick. 像使用'$scope'一样,将'$rootScope'包含到控制器中就可以了。

There's also the $parent attribute of the $scope which could come in handy, but IMO it tends to make code less maintainable if abused. $scope$parent属性也可以派上用场,但是IMO倾向于使代码在被滥用时难以维护。 In particular when multiple scopes are nested, as you need to traverse the whole hierarchy. 特别是当嵌套多个作用域时,您需要遍历整个层次结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM