共享服务的模型是't在AngularJS中更新
Model of a shared service isn't updating in AngularJS
使用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/
相关文章:
- 如何在范围值更改时使用 angularJs 更新 UI
- 使用AngularJS更新cookie
- AngularJS更新控制器变量并再次渲染视图
- Angularjs 更新 setTimeout 中的范围变量不起作用
- 无法使用AngularJS更新变量
- 使用AngularJS更新下拉列表
- AngularJs 更新引导进度条
- AngularJS:更新资源的正确方法是什么
- AngularJS更新$scope变量并输出到pre
- 如何使用AngularJS更新/编辑数据库中的数据
- AngularJS更新ng-model的值以设置默认值
- AngularJs:更新事件$scope
- 使用 AngularJS 更新服务器
- 使用 AngularJS 更新表中的值的最佳实践
- Angularjs - 更新同一控制器的多个实例
- AngularJS更新范围$q
- angularJS更新第二数组值的数组基
- 尝试使用Firebase facebookconnect和AngularJS更新范围变量时出现问题
- 点击AngularJS更新Firebase中的字段
- 使用AngularJS更新Youtube上的400个错误请求