Question-$watch vs $on
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">
{{p}}{{currencyCode}}
</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;
}
};
});
/*
function ControllerA($scope, myService) {
$scope.prices = [10,7,2,12,11,15];
$scope.currencyCode = myService.getCurrency();
$scope.myService = myService;
$scope.$watch("myService.getCurrency()", function() {
$scope.currencyCode = myService.getCurrency();
});
}
*/
function ControllerA($scope, myService) {
$scope.prices = [];
for (var i = 0; i < 500; i ++) {
var rnd = Math.floor(Math.random()*9999999);
$scope.prices.push(rnd)
}
$scope.currencyCode = myService.getCurrency();
$scope.$on("currencyChanged", function() {
$scope.currencyCode = myService.getCurrency();
});
}
function ControllerB($scope, myService) {
$scope.changeCurrency= function() {
myService.randomCurrency();
}
}