In my mainCtrl I have the function add() and use $broadcast to broadcast my 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 a second controller for my popup using $on to receive the broadcast:
No data seems to be passed to my second controller, the expression doesn't show anything at all.
EDIT
I have also tried using a service, HTML's above remain the same but now I've added a service
module.factory('myService', function () {
var total = 0;
var setTotal = function (x) {
total = x;
}
var getTotal = function () {
return total;
};
return {
setTotal: setTotal,
getTotal: getTotal
}
});
My main controller and ad function are now:
module.controller("mainCtrl", function ($scope, myService) {
var total = 0
$scope.add = function (x) {
myService.setTotal(x)
}
});
and my popupCtrl controller is now this :
module.controller('popUpCtrl', function ($scope, myService) {
$scope.total = myService.getTotal();
})
{{total}} in my popup is now being expressed as the "0" which var total is equal to in my service. So the data is now being transferred using the service, but the setTotal() method isn't setting the var as instructed by the add() function now. I have injected my service as a dependency to both controllers.
解决方案
I did find a solution to my initial question, which was to use localStorage.setItem("num", "num") to store the data in the browser. It seems this was developed specifically to share data between tabs/windows, and so is accessible via localStorage.getItem("num").
This answers my original question, however I would now like the total to be updated dynamically. At the moment it is only updated upon refresh. Any tips would be appreciated.
EDIT (ANSWER TO ABOVE)
By using this event listener in my second popup -
window.addEventListener('storage', function (event) {
$scope.total = parseInt(event.newValue);
$scope.$apply();
});
I was able to access the storage and bind it to an expression in my HTML. Bear in mind $scope.apply() needs to be called here because total is outside of the scope.