Referring to this question AngularJS trigger and watch object value change in service from controller
It is trying to watch for changes in a service from a controller. Im trying to extend it to handle multiple module (concurrent app in same page's different div's) communication.
Problem:
I want to achieve the similar feat, but with slight different scenario. I have two modules myApp and yourApp for example. myApp has a service. I want to watch changes in myApp's service within yourApp module's controller. Can it be done? or is there different method to reflect and detect data changes of one module inside another module.
Consider the example code below:
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-click="setFTag()">Click Me</div>
</div>
</div>
<div ng-app="yourApp">
<div ng-controller="yourCtrl">
</div>
</div>
Javascript
// myApp module
var myApp = angular.module('myApp',[]);
// myApp's service
myApp.service('myService', function() {
this.tags = {
a: true,
b: true
};
this.setFalseTag = function() {
alert("Within myService->setFalseTag");
this.tags.a = false;
this.tags.b = false;
//how do I get the watch in YourCtrl of yourApp module to be triggered?
};
});
// myApp's controller
myApp.controller('MyCtrl', function($scope, myService) {
//$scope.myService = myService;
$scope.setFTag = function() {
alert("Within MyCtrl->setFTag");
myService.setFalseTag();
};
/*
$scope.$watch(function () {
return myService.tags;
}, function(newVal, oldVal) {
alert("Inside watch");
console.log(newVal);
console.log(oldVal);
}, true);
*/
});
// yourApp module (Injecting myApp module into yourApp module)
var yourApp = angular.module('yourApp',['myApp']);
// yourApp's controller
yourApp.controller('YourCtrl', function($scope, myService) {
$scope.$watch(function () {
return myService.tags;
}, function(newVal, oldVal) {
alert("Inside watch of yourcontroller");
console.log(newVal);
console.log(oldVal);
}, true);
});
Note: I am not sure if this is the right way to communicate between modules. Any suggestion or the solution will be highly appreciated.
P.S. Ive bootstrapped two modules to fit into same page.