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(){
var self = this;
return {
myVariable: self.myVariable
};
};
} );
myApp.directive( "dir1", function(){
return {
restrict: 'EA',
template: '<div></div>',
replace: true,
link: function( scope, element, attrs ){
scope.init();
scope.$watch( "myVariable.value", function( newVal, oldVal ){
if( newVal === oldVal ){
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.myVariable = myService.myVariable;
};
} ] );
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope, myService ){
$scope.increaseVal = function(){
var a = myService.myVariable.value;
myService.myVariable.value = a + 1;
};
} ] );