如何避免在嵌套作用域中使用$ parent.$ parent.$ parent [英] How to avoid using `$parent.$parent.$parent` in nested scopes

查看:53
本文介绍了如何避免在嵌套作用域中使用$ parent.$ parent.$ parent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular的新手,所以我有一个基本问题.

I'm new to Angular so I have one basic question.

假设,在Angular中,我有一个如下所示的控制器链.

Suppose, In Angular, I have a controller's chain like below.

<div ng-controller="parentController">
  ... something in the parent element
  <div ng-controller="childController">
     ... something in the child element
  </div>
</div>

有什么方法可以在子元素中编写代码,以便我可以在输出中知道父控制器的名称(在这种情况下,输出应为"parentController")?

Is there any way to write the code in the child element so that I can know the parent controller name in the output (In this case output should be 'parentController')?

我需要这个是因为我有一个太大的项目,并且想知道每个控制器的父级,因为有人写了类似的代码

I need this because I have a too big project and want to know the parent of each controller because someone has wrote the code like

googleOAuth= $scope.$parent.$parent.$parent.$parent.status.googleOAuth

我无法理解,所以想知道每个$ scope的父级.

and I'm not able to understand so want to know the parent of each $scope.

推荐答案

正如georgeawg所说,使用$ parent并不是最佳选择,因为它依赖于恒定数量的作用域.

As georgeawg said, using $parent is not optimal because it relies on a constant number of scopes.

相反,您可以编写服务来处理googleOAuth.然后可以将该服务注入每个控制器中,并作为单一事实来源,因为服务是AngularJS中的单例.

Instead, you could write a service to deal with your googleOAuth. The service can then be injected in each controller and will function as a single source of truth because services are singletons in AngularJS.

例如像这样的东西

angular.module('appModule', [])
    .factory('googleOAuthService', [function() {
        var googleOAuth = {
            // your googleOAuth stuff here
        };

        return {
            get: get,
            set: set,
            stuff: stuff
        }

        function get () {
            return googleOAuth;
        }

        function set (newGoogleOAuth) {
            googleOAuth = newGoogleOAuth;
        }

        function stuff () {
            // Do stuff to googleOAuth
        }
    }])
    .controller('parentController', ['googleOAuthService', function(googleOAuthService) {
        googleOAuthService.stuff();
    }])
    .controller('childController', ['googleOAuthService', function(googleOAuthService) {
        googleOAuthService.stuff();
    }]);

有关更多信息,请参见 https://docs.angularjs.org/guide/services

For more info, see https://docs.angularjs.org/guide/services

这篇关于如何避免在嵌套作用域中使用$ parent.$ parent.$ parent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆