使用AngularJS ,我有两个 Controller 在我的应用程序中共享相同的服务。
当我触发由 portalController
函数控制的事件(请参阅 setLang()
)时,我没有看到 applicationController 的模型被更新。
此问题似乎仅在 Firefox 和 Chrome 中出现。在 IE8 中,它出乎意料地工作正常。
门户 Controller
(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'];
}());
应用程序 Controller
(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
最佳答案
问题是我使用的是 $scope 而不是 $rootScope,
数据通过服务中的第一个 Controller 进行更新,但没有任何信息通知第二个 Controller 此更改:
第一个 Controller 中通知 $rootScope 更改的代码
$scope.setLang = function(locale){
$rootScope.data = sharedService.getData(locale);
};
第二个 Controller 中的代码监视变化
$rootScope.$watch('data', function(newValue) {
$scope.data = newValue;
});
下面是“错误” fiddle 的链接,当其他人也遇到此问题时,该链接适用:
错误:http://jsfiddle.net/GFVYC/1/
工作一:http://jsfiddle.net/GFVYC/4/
关于javascript - AngularJS 中的共享服务模型未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18058077/