角度模态>Ctrl+gt;服务>Ctrl继承不起作用
Angular Modal>Ctrl>Service>Ctrl inheritance not working
我正在尝试将模型链接到服务,这将允许我在整个应用程序中更新全局模型,但它似乎没有像预期的那样工作。
我最近开始研究AngularJS,所以我可能误解了我的代码,但从我的理解来看,服务将作为实例工作,而不是工厂单例,工厂单例应该允许我使用服务来控制所有$scoped模型。
我正试着把我的模型链接成这样:
模型:{{language.title}}
> ctrl1:$scope.language=langSrvic.store;
>> srvic:langSrvic.store=myFactory;
> ctrl2:langSrvic.set('locale','fr');
>>语言实例存储已更新(应反映控制器1型号的变化)
jsFiddle的我的工作代码
//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>
您正在引用不同的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
}
请参阅更新的fiddle以获得修复:http://jsfiddle.net/3c7ube0s/1/
相关文章:
- 在<页眉>标签
- 如何更改<svg>标记为<img>用js标记
- Ckeditor-plugin:插入虚假元素add不情愿<p>标签前后
- Ajax文件加载和<输入>文件加载
- 为什么要使用0>javascript中的0
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 链接所有<a>Meteor
- 在<输入类型=“;文件“/>
- Div根据<选择>菜单
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- 如何首先设置样式<td>表中包含在窗体中的元素
- 通过点击<李>在jQuery中
- 正在检测导航到<a name=“;最新主题”></a>
- 将所选类别循环到ul>李用加载更多按钮
- 如何更改<选择>使用angularJS从控制器获得的值
- 使用下拉列表筛选列表(ul>li)
- 这个问号在Flow中意味着什么:“;?()=>“无效”;
- 如何附加<ul><李>元素位于某个特定条件的父元素列表之间
- 角度模态>Ctrl+gt;服务>Ctrl继承不起作用
- 如何发送'ctrl+end'键<text区域>元素,使光标落在最后一个字符之后