角度模态>Ctrl+gt;服务>Ctrl继承不起作用

Angular Modal>Ctrl>Service>Ctrl inheritance not working

本文关键字:gt Ctrl 继承 不起作用 服务 模态 Ctrl+gt      更新时间:2023-09-26

我正在尝试将模型链接到服务,这将允许我在整个应用程序中更新全局模型,但它似乎没有像预期的那样工作。

我最近开始研究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/