简体   繁体   English

AngularJS:在视图上多次使用同一控制器

[英]AngularJS: Using the same controller multiple times on a view

I am delving into Angularjs and got to the point where I am taking my application beyond the simple todo list stages. 我正在研究Angularjs,以至于使我的应用程序超出了简单的待办事项清单阶段。

A scenario I have, which must be common, is to have one controller that needs to be shared across multiple areas on my view. 我遇到的一个场景(必须很常见)是拥有一个控制器,该控制器需要在我视图的多个区域中共享。

In my case I have a profileController which I want to use to get the profile of the user from the server on each load. 在我的情况下,我有一个profileController,我想使用它在每次加载时从服务器获取用户的配置文件。

When calling the loadUserProfile from within the profileController I saw that it was called 'n'-times (for the number of times I referenced the controller on the view), which is cool, so I changed the profileController to simply expose variables such as userProfile and isAuthenticated which simply references variables that I set in the $rootScope. 当从profileController中调用loadUserProfile时,我看到它被称为“ n”次 (对于我在视图上引用控制器的次数),这很酷,因此我更改了profileController,以简单地公开诸如userProfile之类的变量和isAuthenticated仅引用我在$ rootScope中设置的变量。 These variables are set in a controller that is loaded once per page declared on my <body data-ng-controller="baseController as vm"> , however this does not seem to work, and I am wondering what I am missing. 这些变量是在一个控制器中设置的,该控制器每页在<body data-ng-controller="baseController as vm">上声明的页面中加载一次,但是这似乎不起作用,我想知道自己缺少什么。

So it get's the data from the profileService, but when updating the $rootScope variables, it does not reflect it on my view. 因此它是从profileService获取的数据,但是在更新$ rootScope变量时,它不会在我的视图中反映出来。

Below is my baseController: 下面是我的baseController:

(function () {
    'use strict';

    var controllerId = 'baseController';
    angular.module('app.controllers').controller(controllerId, ['$location', 'common', 'authClientSvc', 'profileService', '$rootScope', baseController]);

    function baseController($location, common, authClientSvc, profileService, $rootScope) {
        var getLogFn = common.logger.getLogFn;
        var log = getLogFn(controllerId);
        var vm = this;

        $rootScope.isAuthenticated = false;
        $rootScope.userProfile = {
            email: '',
            name: '',
            surname: ''
        };


        activate();

        function activate() {
            var promises = [getUserProfile()];
            common.activateController([promises], controllerId)
                .then(function () { log('Activated Secure View'); });
        }

        function getUserProfile() {
            profileService.getProfile('a@a.com').then(function (data) {
                setTimeout(function () {
                    $rootScope.$apply(function () {
                        $rootScope.userProfile = data;
                        $rootScope.isAuthenticated = authClientSvc.isAuthenticated()
                    })
                }, 1000);
            });
        }
    }
})();

And my profileController where I expose the $rootScope variables below: 在我的profileController中,我在下面公开了$ rootScope变量:

(function () {
    'use strict';

    var controllerId = 'profileController';
    angular.module('app')
        .controller(controllerId, ['common', 'authClientSvc', 'profileService', '$rootScope', profileController]);

    function profileController(common, authClientSvc, profileService, $rootScope) {
        var getLogFn = common.logger.getLogFn;
        var log = getLogFn(controllerId);

        var vm = this;

        vm.logoutUrl = '/';

        vm.isAuthenticated = $rootScope.isAuthenticated;
        vm.profile = $rootScope.userProfile;

        activate();

        function activate() {
            var promises = [];
            common.activateController(promises, controllerId)
                .then(function () { log('Activated Profile controller'); });
        }

        vm.logOut = function () {
            authClientSvc.logout();
        }
    }
})();

I am not sure what is wrong, because in Fiddler I can clearly see the data coming back, and when I debug it and put log messages in the baseController after if gets the profile, it gets back the right data, but for some reason it is not working on my elements. 我不确定是哪里出了问题,因为在Fiddler中,我可以清楚地看到数据返回,并且在调试它并将日志消息放入baseController后,如果获取了配置文件,它将获取正确的数据,但是由于某种原因,它会返回正确的数据。对我的元素不起作用。 Below is a sample of how I use it on the view: 以下是我如何在视图上使用它的示例:

<div class="login-info" data-ng-controller="profileController as vm">
    <span ng-switch="vm.isAuthenticated">
        <a ng-switch-when="true" href="javascript:void(0);" id="show-shortcut" data-action="toggleShortcut">
            <img src="/Content/img/avatars/male.png" alt="me" class="online" />
            <span data-localize="{{vm.profile.name}}.{{vm.profile.surname}}">
                {{vm.profile.name}}.{{vm.profile.surname}}
            </span>
            <i class="fa fa-angle-down"></i>
        </a>
        <span ng-switch-when="false">
            <img src="/Content/img/avatars/male.png" alt="guest" class="online" />
            <span data-localize="Guest.user">
                Guest User
            </span>
        </span>
    </span>
</div>

Any help would be greatly appreciated, or even suggestions on how to achieve this in a better way. 我们将不胜感激任何帮助,甚至提供有关如何以更好的方式实现此目标的建议。

Thanks. 谢谢。

According to Angular documentation : 根据Angular 文档

When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. 当通过ng-controller指令将Controller附加到DOM时,Angular将使用指定的Controller的构造函数实例化一个新的Controller对象。 A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope. 新的子作用域将作为控制器的构造函数(作为$ scope)的可注入参数可用。

Meaning: Controllers are instantiated when the ng-controller directive is attached to the DOM. 含义:当ng-controller指令附加到DOM时,实例化控制器。 If you have two ng-controllers, then you will have two separate instances of ng-controller. 如果您有两个ng-controller,则将有两个单独的ng-controller实例。

And

Do not use controllers to: 请勿使用控制器执行以下操作:

  • Share code or state across controllers — Use angular services instead. 在控制器之间共享代码或状态-改为使用角度服务。

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

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