$scope.$on not updating controller property


#1

I have an Angular/Ionic app that uses the Network Phonegap API to check for network connection. I have defined event handlers to handle online/offline events. When these events occur, I broadcast events through the $rootScope $broadcast method. In my controller, I listen for this event using the $on method and update a scope property. The scope property is bound to the view to disable a button when there is no internet connection. The problem is the scope property is not set even when the offline/online events are fired (Tested on my Samsung S3). My code for clarity:

document.addEventListener("offline", function() {
    //broadcast offline event to controllers
    $rootScope.$broadcast("networkStatusChange", 'Offline');
}, false);

document.addEventListener("online", function() {
    $rootScope.$broadcast("networkStatusChange", 'Online');
}, false);

My CONTROLLER

    $scope.$on('networkStatusChange', function(event, status) {
        $scope.networkInfo.isOffline = status === 'Offline' ? true : false;
    });

$scope.networkInfo = {}; //bound to view to disable button is isOffline is true

MY VIEW

<p class="error" ng-show="networkInfo.isOffline">No Internet Connection.</p>

I don’t know why the networkInfo.isOffline property is not changing when I switch on/off my phone’s internet connection.


#2

Hey there,

you are mixing native javascript events (document.addEventListener) with angular events.
Keep in mind angularjs is responsible for your databinding, if you are using native javascript events angularjs does not really recognize things you change in there.

Use $timeout or $scope.$apply to trigger a new digest when you are using javascript events.

  1. Load $timeout as dependency in your controller
document.addEventListener("offline", function() {
    //broadcast offline event to controllers
    $timeout(function () {
        $rootScope.$broadcast("networkStatusChange", 'Offline');
    });
}, false);