1

我試圖將模型鏈接到服務,這將允許我在整個應用程序中更新全局模型,但它似乎沒有按預期工作。Angular Modal> Ctrl> Service> Ctrl繼承不起作用

我最近開始關注AngularJS,所以有可能我誤解了我的代碼,但是我知道服務將作爲一個實例工作,反對一個工廠單例,它應該允許我使用服務來控制所有$範圍內的模型。

我想我的連鎖模式是這樣的:

型號: {{language.title}}

>>>CTRL 1: $ scope.language = langSrvic.store ;

>>>srvic: langSrvic.store = myFactory;

>>>CTRL2: langSrvic.set( '區域設置', 'FR');更新

>>>語言實例存儲(應反映在控制器1種模式的變革)

jsFiddle of my working code

//Application 
 
var app = angular.module('app',[]); 
 

 
//Controller 1 
 
app.controller('first', ['$scope', 'language', function($scope, language){ 
 
\t $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){ 
 
\t return { 
 
\t \t locale: 'en', 
 
\t \t store: i18n['en'], 
 
\t \t set: function(prop, val){ 
 
\t \t \t this[prop] = val; 
 
\t \t \t this.store = i18n[this.locale]; 
 
\t \t } 
 
\t } 
 
}]); 
 

 
//Factory - storing instead of an api temporarily 
 
app.factory('i18n', [function(){ 
 
\t return { 
 
\t \t en:{ 
 
\t \t \t title: 'My application' 
 
\t \t }, 
 
\t \t fr:{ 
 
\t \t \t title: 'Something something french' 
 
\t \t }, 
 
\t } 
 
}]); 
 

 
//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>

回答

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/

+0

謝謝你,我不知道我怎麼錯過了這個:)將在幾分鐘內接受時,其可用。 – 2014-10-27 09:48:41