JSFiddle - React, Tailwind, and code Playground
HTML
<body ng-app = "myApp">
<div dir1 ng-controller = "ctrl1">
</div>
<div ng-controller = "ctrl2">
<button ng-click = "increaseVal()">
Increase
</button>
</div>
</body>
JavaScript
var myApp = angular.module( "myApp", [] );
myApp.provider( "myService", function(){
this.myVariable = {
value: 0
};
this.$get = function( $injector ){
var self = this;
var rootScope = $injector.get( "$rootScope" );
return {
myVariable: self.myVariable,
increaseVal: function(){
var a = self.myVariable.value;
self.myVariable.value = a + 1;
rootScope.$broadcast( "increased" );
}
};
};
} );
myApp.directive( "dir1", function(){
return {
restrict: 'EA',
template: '<div></div>',
replace: true,
link: function( scope, element, attrs ){
scope.init();
scope.$watch( "increasedCounter", function( newVal, oldVal ){
if( newVal === oldVal ){
alert("done")
return;
}
while( element[0].children.length > 0 ){
element[0].removeChild( element[0].firstChild );
}
var e = angular.element( element );
e.append( "<span>Value is: " + scope.myVariable.value + "</span>" );
} );
}
};
} );
myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope, myService ){
$scope.init = function(){
$scope.increasedCounter = 1;
$scope.myVariable = myService.myVariable;
};
$scope.$on( "increased", function(){
$scope.increasedCounter += 1;
} );
} ] );
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope, myService ){
$scope.increaseVal = function(){
myService.increaseVal();
};
} ] );