I need to call a function from another controller in Angular JS. Another question on Stack Overflow suggests to use a service instead: https://stackoverflow.com/a/11847277/1910735
JSFiddle: http://jsfiddle.net/0z7ux66c/
So I created a service, and two controllers:
var app = angular.module("myApp", []);
app.factory('trackingService', function ($rootScope) {
var trackingInstance = {};
trackingInstance.assetInformationModel = null;
trackingInstance.RefreshDashboard = function () {
$rootScope.$broadcast('Refresh');
};
return trackingInstance;
});
app.controller('assetInformationController', function ($scope, trackingService) {
$scope.UpdateDashboard = function () {
console.log('UpdateDashboard()')
trackingService.RefreshDashboard();
};
$scope.$on('Refresh', function () {
// THIS gets called
console.log('Refresh');
});
});
app.controller('liveTrackingController', function ($scope, trackingService){
$scope.$on('Refresh', function () {
// THIS doesn't
console.log('Refresh in liveTrackingController');
});
});
From the code, it should display the following three lines in Console:
UpdateDashboard()
Refresh
Refresh in liveTrackingController
But it is not calling the Reresh
Event from liveTrackingController
- It is only displaying:
UpdateDashboard()
Refresh