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

时间:2014-09-09 06:04:59

标签: angularjs angularjs-scope

我正在深入研究Angularjs,并且我已经将我的应用程序带到了简单的待办事项列表阶段之外。

我拥有的一个必须通用的场景是,需要在我的视图中的多个区域共享一个控制器。

在我的情况下,我有一个profileController,我想在每次加载时使用它来从服务器获取用户的个人资料。

当从profileController中调用loadUserProfile时,我看到它被称为&#39; n&#39; -times (我在视图中引用控制器的次数),很酷,所以我更改了profileController以简单地公开变量,如userProfile和isAuthenticated,它只引用我在$ rootScope中设置的变量。这些变量是在一个控制器中设置的,每个页面在<body data-ng-controller="baseController as vm">上声明加载一次,但是这似乎不起作用,我想知道我错过了什么。

因此它获取了来自profileService的数据,但是在更新$ rootScope变量时,它并没有在我的视图中反映出来。

下面是我的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变量:

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

我不确定是什么问题,因为在Fiddler中我可以清楚地看到数据返回,当我调试它并在获取配置文件之后将日志消息放入baseController后,它会获取正确的数据,但是某种原因,它不适用于我的元素。以下是我在视图中使用它的示例:

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

非常感谢任何帮助,甚至建议如何以更好的方式实现这一目标。

感谢。

1 个答案:

答案 0 :(得分:12)

根据Angular documentation

  

当Controller通过ng-controller指令附加到DOM时,Angular将使用指定的Controller的构造函数实例化一个新的Controller对象。新的子作用域将作为$ scope的构造函数的可注入参数提供。

含义:当ng-controller指令附加到DOM时,控制器被实例化。如果你有两个ng-controller,那么你将有两个独立的ng-controller实例。

  

请勿使用控制器:

     
      
  • 跨控制器共享代码或状态 - 改为使用角度服务。
  •