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

2023-09-14 00:20:20 作者:Review(旧爱)

我钻研Angularjs,得到的地步,我以我的应用程序超出了简单的待办事项列表阶段。

I am delving into Angularjs and got to the point where I am taking my application beyond the simple todo list stages.

一个场景我有,它必须是共同的,就是有一个控制器,需要在多个领域对我的看法共享。

A scenario I have, which must be common, is to have one controller that needs to be shared across multiple areas on my view.

在我来说,我有我要用来从每个负载服务器获取用户的配置文件的ProfileController可。

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.

在调用loadUserProfile从ProfileController可在我看到它被称为的N'-二倍的(对的次数我引用的视图控制器),这是很酷,所以我改变了ProfileController可简单地暴露变量,如用户配置文件和isAuthenticated它只是引用了我在$ rootScope设置变量。体数据-NG-控制器=baseController为VM> ,然而这并没有这些变量在每在我的&LT声明页面加载一次控制器设置似乎工作,我想知道我错过了什么。

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. 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.

因此​​,它得到的从profileService的数据,但更新$ rootScope变量时,它不反映它放在我的看法。

So it get's the data from the profileService, but when updating the $rootScope variables, it does not reflect it on my view.

下面是我的baseController:

Below is my 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);
            });
        }
    }
})();

和我ProfileController可在那里我揭露低于$ rootScope变量:

And my profileController where I expose the $rootScope variables below:

(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();
        }
    }
})();

我不知道什么是错的,因为在提琴手我可以清楚地看到数据回来,当我调试它,并把记录在baseController的消息后,如果得到的配置文件,它就会回到正确的数据,但对于由于某种原因,它不工作对我的元素。下面是我如何使用它的视图的例子:

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. 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>

任何帮助将大大AP preciated,或者对如何以更好的方式实现这一目标,甚至建议。

Any help would be greatly appreciated, or even suggestions on how to achieve this in a better way.

感谢。

推荐答案

据角文档

当一个控制器连接到通过NG-控制器指令中的DOM,角将实例化一个新的控制器对象,使用指定的控制器的构造函数。一个新的子范围,将可作为注射参数传递给控制器​​的构造函数为$范围。

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. A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope.

含义:当纳克控制器指令附加到DOM控制器被实例化。如果你有两个NG-控制器,那么你将有NG-控制器的两个单独的实例。

Meaning: Controllers are instantiated when the ng-controller directive is attached to the DOM. If you have two ng-controllers, then you will have two separate instances of ng-controller.

不要使用控制器:

  跨控制器分享code或状态 - 使用角度,而不是服务