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 () {
console.log(this);
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;
console.log("app2");
console.log(sharedService);
};
sharedService.registerObserverCallback(updateCountry);
// 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("App1:");
console.log(sharedService);
sharedService.Country = $scope.Country;
sharedService.notifyObservers();
// this is not working because the rootscope is not shared
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-app="app1" ng-controller="app1Controller" align="left">
This App1
<select id="country" ng-change="DrpChange()" ng-model="Country">
<option ng-repeat="ct in Countries" value="{{ct}}">{{ct}}</option>
</select>
</div>
<div id="app2" align="left" style="padding:30px">
This is App2
<div ng-controller="app2Controller">
Selected Country is {{myCountry}}
</div>
</div>
<!-- We'll also add some navigation: -->
<script>
angular.bootstrap(document.getElementById("app2"), ['app2']);
</script>
</body>
</html>
/* Put your css in here */