我正在尝试将模型链接到服务,这将允许我在整个应用程序中更新全局模型,但它似乎没有按预期工作。
我最近开始研究AngularJS所以我可能会误解我的代码,但是据我所知,服务将作为一个实例工作,反对工厂单例,这应该允许我使用服务来控制所有$ scoped模型。
我试图像这样链接我的模型:
型号: {{language.title}}
>>> ctrl1: $ scope.language = langSrvic.store;
>>> srvic: langSrvic.store = myFactory;
>>> ctrl2: langSrvic.set('locale','fr');
>>> 语言实例存储更新(应反映控制器1模型中的更改)
//Application
var app = angular.module('app',[]);
//Controller 1
app.controller('first', ['$scope', 'language', function($scope, language){
$scope.language = language.store;
setTimeout(function(){
console.log($scope.language.title); //My application
console.log(language.store.title); //Something something french
}, 1500);
}]);
//Language service
app.service('language', ['i18n', function(i18n){
return {
locale: 'en',
store: i18n['en'],
set: function(prop, val){
this[prop] = val;
this.store = i18n[this.locale];
}
}
}]);
//Factory - storing instead of an api temporarily
app.factory('i18n', [function(){
return {
en:{
title: 'My application'
},
fr:{
title: 'Something something french'
},
}
}]);
//Controller 2 - changing locale to fr which should update the instance store and so update the first scope
app.controller('second', ['$scope', 'language', function($scope, language){
language.set('locale', 'fr');
$scope.language = language.store;
}]);
<div ng-controller="first">
{{ language.title }}
<div ng-controller="second">
{{ language.title }}
</div>
</div>
答案 0 :(得分:1)
您正在引用其他store
对象:
set: function(prop, val){
this[prop] = val;
this.store = i18n[this.locale]; // this line sets language.store to the new object but Controller 1 is referencing the old one
}
请参阅更新的小提示以获取修复:http://jsfiddle.net/3c7ube0s/1/