JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.angularjs.org/1.3.8/angular.js"></script>
<div ng-app="myApp" >
<div ng-controller="myController1" >
myController1:
<button ng-click="sendmsg()">send</button>
</div>
<div ng-controller="myController2" >myController2:{{data.date}}</div>
<div ng-controller="myController3 as vm" >myController3:{{vm.data.date}}</div>
<div my-directive="" > </div>
</div>
JavaScript
angular.module("myApp",[]);
angular.module("myApp").factory('dataService', function() {
var obj ={};
var observerCallbacks = [];
return {
set:set,
get:get,
register: register,
notifyObservers: notifyObservers
};
function register(callback){
observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
function notifyObservers(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
function set(data) {
obj=data;
notifyObservers();
};
function get() {
return obj;
};
});
angular.module("myApp").controller("myController1", function ($scope,dataService) {
$scope.sendmsg = function() {
var date=new Date();
dataService.set({'date':date});
};
});
angular.module("myApp").controller("myController2", function($scope, dataService) {
$scope.data={'date':""};
function updateData(){
$scope.data = dataService.get();
};
dataService.register(updateData);
});
angular.module("myApp").controller("myController3", function (dataService){
var vm=this;
vm.data={'date':""};
function updateData(){
vm.data = dataService.get();
};
dataService.register(updateData);
});
angular.module("myApp").directive('myDirective', function(dataService) {
function link(scope, element, attrs) {
scope.data={'date':""};
function updateData(){
scope.data = dataService.get();
};
dataService.register(updateData);
};
return {
scope:{},
link: link,
template: 'myDirective: {{ data.date }}'
};
});