共享服务的模型是't在AngularJS中更新

Model of a shared service isn't updating in AngularJS

本文关键字:AngularJS 更新 服务 模型 共享      更新时间:2023-09-26

使用AngularJS,我的应用程序中有两个控制器共享相同的服务。当我触发由portalController函数控制的事件(请参阅setLang())时,我看不到applicationController的模型正在更新。

这个问题似乎只出现在Firefox和Chrome上。在IE8中,它出乎意料地运行良好。

PortalController

(function () {
'use strict';
var controllers = angular.module('portal.controllers');
controllers.controller('portalController', function portalController($scope, UserService, NavigationService, $translate) {
    $scope.User = UserService.getUserinfo();
    $scope.setLang = function (langKey) {
        $translate.uses(langKey);
        UserService.setUserinfoLocale(langKey);
        UserService.getUserApplications(Constants.key_ESS);
        UserService.getUserApplications(Constants.key_MED);
        UserService.getUserApplications(Constants.key_SVF);
        $.removeCookie(Constants.cookie_locale);
        var domain = document.domain;
        if (domain.indexOf(Constants.context_acc) != -1 || domain.indexOf(Constants.context_prd) != -1 || domain.indexOf(Constants.context_tst) != -1) {
            domain = "." + domain;
            $.cookie(Constants.cookie_locale, langKey, {path:"/", domain:domain});
        } else {
            $.cookie(Constants.cookie_locale, langKey, {path:"/"});
        }
    };
    $scope.logout = function () {
        NavigationService.logout();
    };

    $translate.uses(UserService.getUserinfoLocale());

});
//mainController.$inject = ['$scope','UserInfo'];

}());

应用程序控制器

(function () {
'use strict';
var controllers = angular.module('portal.controllers');
controllers.controller('applicationController', function ($scope, UserService) {
    $scope.ESS = UserService.getUserApplications(Constants.key_ESS);
    $scope.SVF = UserService.getUserApplications(Constants.key_SVF);
    $scope.MED = UserService.getUserApplications(Constants.key_MED);
});
}());

共享的UserService

UserService.prototype.getUserApplications = function(entity){
    var locale = this.getUserinfoLocale();
        return this.userApplications.query({locale: locale, entity: entity});
};

JSFiddle

http://jsfiddle.net/GFVYC/1/

问题是我使用的是$scope而不是$rootScope,
数据通过服务中的第一个控制器更新,但没有任何信息通知第二个控制器这一变化:

第一个控制器中通知$rootScope更改的代码

$scope.setLang = function(locale){
        $rootScope.data = sharedService.getData(locale);
};

第二个控制器中的代码监视更改

    $rootScope.$watch('data', function(newValue) {
        $scope.data = newValue;
    });

以下是"错误"小提琴的链接,适用于其他人也有这个问题的情况:

错误的一个:http://jsfiddle.net/GFVYC/1/
工作一:http://jsfiddle.net/GFVYC/4/