Angularjs Observable Update
Upated
by bkarv
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.5/angular-material.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.5/angular-material.min.css">
<script src="https://cdn.jsdelivr.net/rxjs/4.1.0/rx.all.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
<style>
.table-cell{
border-right:1px solid black;
}
</style>
<script type="text/ng-template" id="/boxa">
BoxA - Message Listener: </br>
<strong>{{boxA.msg}}</strong></br>
<button ng-click="boxA.unsubscribe()">Unsubscribe A</button>
</script>
<script type="text/ng-template" id="/boxb">
BoxB - Message Listener: </br>
<strong>{{boxB.msg}}</strong></br>
<button ng-click="boxB.unsubscribe()">Unsubscribe B</button>
</script>
<md-content class='md-padding'>
<h3>
{{name}}
</h3>
<label>Enter Text To Broadcast</label>
<input ng-model='msg'/></br>
<md-button class='md-primary' ng-click='broadcastFn()'>Broadcast</md-button></br>
<h4>
Components
</h4>
<box-a></box-a></br>
<box-b></box-b>
</md-content>
</div><!--end app-->
JavaScript
var app = angular.module('myApp', ['ngMaterial']);
app.controller('mainCtrl', function($scope,msgService) {
$scope.name = "Observer App Example";
$scope.msg = 'Message';
$scope.broadcastFn = function(){
msgService.broadcast($scope.msg);
}
});
app.component("boxA", {
bindings: {},
controller: function(msgService) {
var boxA = this;
boxA.msgService = msgService;
boxA.msg = '';
var boxASubscription = boxA.msgService.subscribe(function(obj) {
console.log('Listerner A');
boxA.msg = obj;
});
boxA.unsubscribe = function(){
console.log('Unsubscribe A');
boxASubscription.dispose();
};
},
controllerAs: 'boxA',
templateUrl: "/boxa"
})
app.component("boxB", {
bindings: {},
controller: function(msgService) {
var boxB = this;
boxB.msgService = msgService;
boxB.msg = '';
var boxBSubscription = boxB.msgService.subscribe(function(obj) {
console.log('Listerner B');
boxB.msg = obj;
});
boxB.unsubscribe=function(){
console.log('Unsubscribe B');
boxBSubscription.dispose();
};
},
controllerAs: 'boxB',
templateUrl: "/boxb"
})
app.factory('msgService', ['$http', function($http){
var msgSubject = new Rx.Subject();
return{
subscribe:function(subscription){
return msgSubject.subscribe(subscription);
},
broadcast:function(msg){
console.log('success');
msgSubject.onNext(msg);
}
}
}])