I've been struggling with utilizing $broadcast and $on functions to transfer data between two controllers.
On my main webpage, there is a button that increments a variable by 4 each time it's clicked:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body ng-app="app">
<div ng-controller="mainCtrl">
<button ng-click="add(4)"> 4 </button>
</div>
<script src="../Scripts/angular.js"></script>
<script src="../assets/js/angular-grid.js"></script>
<script src="../assets/controller/gods_controller.js"></script>
<script src="../Scripts/angular-animate.js"></script>
</body>
</html>
In my mainCtrl, I have the add() function which uses $broadcast to send out the updated value:
var module = angular.module("app", ["angularGrid", "ngAnimate"])
module.controller("mainCtrl", function ($scope, $rootScope) {
var total = 0
$scope.add = function (x) {
total += x;
$rootScope.$broadcast('totalBroadcast', total)
}
});
Then, I have another controller for a popup using $on to receive the broadcasted data:
module.controller('popUpCtrl', function ($scope) {
$scope.$on('totalBroadcast', function(events, args){
$scope.total = args;
})
})
The HTML for the popup utilizes the second controller and displays {{total}} as an expression:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body ng-app="app">
<div ng-controller="popUpCtrl">
<p>The total is: {{total}}</p>
</div>
<script src="../Scripts/angular.js"></script>
<script src="../assets/js/angular-grid.js"></script>
<script src="../assets/controller/gods_controller.js"></script>
<script src="../Scripts/angular-animate.js"></script>
</body>
</html>
However, no data seems to be passed to the second controller, and the expression shows nothing at all.
EDIT
I also attempted to use a service. The HTML remains the same, but now a service has been added.
module.factory('myService', function () {
var total = 0;
var setTotal = function (x) {
total = x;
}
var getTotal = function () {
return total;
};
return {
setTotal: setTotal,
getTotal: getTotal
}
});
The main controller and add function are now:
module.controller("mainCtrl", function ($scope, myService) {
var total = 0
$scope.add = function (x) {
myService.setTotal(x)
}
});
The popUpCtrl controller is now:
module.controller('popUpCtrl', function ($scope, myService) {
$scope.total = myService.getTotal();
})
{{total}} in the popup now displays the initial "0" which is what the variable total is set to in the service. The data is being transferred using the service, but the setTotal() method doesn't seem to be updating the variable as expected by the add() function. Both controllers have the service injected as a dependency.