我需要知道如何在不同模塊中的兩個控制器之間同步數據。下面是我使用的代碼。我試圖用觀察者模式使用服務。但似乎注入的兩個應用服務實例有很大的不同如何在AngularJS中的兩個獨立模塊之間共享數據
angular.module('app3', []).service('sharedService', function() {
this.Country = 'USA';
this.scope = null;
this. observerCallbacks = [];
//register an observer
this.registerObserverCallback = function (callback) {
this.observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
this.notifyObservers = function() {
alert('notifed');
angular.forEach(this.observerCallbacks, function (callback) {
console.log('notification');
callback();
});
};
})
angular.module('app2', ['app3']).controller('app2Controller', function ($scope, $rootScope, sharedService) {
console.log('Controller 2 loaded');
var updateCountry = function() {
$scope.MyCountry = sharedService.Country;
};
sharedService.registerObserverCallback(updateCountry);
console.log(sharedService);
// this needs lazy loading
// $rootScope = sharedService.scope;
// console.log(sharedService.Country);
// $scope.MyCountry = sharedService.Country;
})
angular.module('app1',['app1','app3']).controller('app1Controller',function($scope,$rootScope,sharedService)
{
$scope.Countries = ['Egypt', 'KSA'];
$scope.Country = '';
sharedService.scope = $rootScope;
$scope.DrpChange = function() {
//$stateParams.Country = $scope.Country;
//$state.current.params.Country = $scope.Country;
//console.log($state.current.params.Country);
console.log(sharedService);
sharedService.Country = $scope.Country;
sharedService.notifyObservers();
// this is not working because the rootscope is not shared
$rootScope.$emit("Country.changed", $scope.Country);
}
})
angular.bootstrap(document.getElementById("app2"), ['app2']);
看到HTML在http://embed.plnkr.co/l0utIMp27qpbsao64Api/
應該是同一個實例。什麼是具體問題? – charlietfl
其實它們並不相同,控制檯的日誌顯示它們不同。如果我們在兩個控制器中都有相同的參考,問題將得到解決。 Object {Country:「USA」,scope:Scope,observerCallbacks:Array [0]} 對象{Country:「KSA」,scope:Scope,observerCallbacks:Array [0]} –
創建一個演示,複製您遇到的任何問題 – charlietfl