Question-Directives which monitors a service
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="ControllerA">
<ul>
<li ng-repeat="p in prices">
<currency baseprice="{{p}}">{{baseprice}}{{currencyCode}}</currency>
</li>
</ul>
</div>
<div ng-controller="ControllerB">
<a ng-click="changeCurrency()">Random Currency</a><br>
</div>
</div>
JavaScript
angular.module('myApp', [])
.service('myService', function ($rootScope) {
var currencies = ["SGD", "INR", "USD", "MYR", "EUR"];
var currency = "SGD";
return {
randomCurrency : function() {
var i = Math.floor(Math.random()*5);
currency = currencies[i];
$rootScope.$broadcast('currencyChanged', currency);
},
getCurrency : function() {
return currency;
}
};
})
.directive('currency', ['myService', function(location) {
return {
restrict: 'E',
scope : {
baseprice : "@"
},
controller : function($scope, $attrs, myService) {
$scope.currencyCode = myService.getCurrency();
$scope.$on("currencyChanged", function(event, args) {
$scope.currencyCode = myService.getCurrency();
});
},
link: function($scope, element, attrs, controller) {
console.log("dummy");
}
};
}]);
function ControllerA($scope, myService) {
$scope.prices = [10,7,2,12,11,15];
}
function ControllerB($scope, myService) {
$scope.changeCurrency= function() {
myService.randomCurrency();
}
}