Kiwi
Kiwi

Reputation: 2773

Angular service on update

I'm making this module that keeps track if the user is online or not, therefor I wrote the following factory

var app = angular.module('cskiwi.general-utilities', [])
.factory('cskiwiUtilities', function ($rootScope, $window) {
    var networkInfo = function() {
        // check if online
        var online = $rootScope.online = window.navigator.onLine;
        $window.addEventListener("offline", function() {
            $rootScope.$apply(function() {
                online = $rootScope.online = false;
            });
        }, false);

        $window.addEventListener("online", function() {
            $rootScope.$apply(function() {
                online = $rootScope.online = true;
            });
        }, false);

        // update changes
        $rootScope.$watch('online', function(newStatus) {
            $rootScope.$broadcast('onlineUpdate', newStatus);
        });

        return { online: online };
    };

    //public methods & properties
    var self = {
        networkInfo: networkInfo
    };


    return self;
});

So now I can do the following: $scope.networkInfo = cskiwiUtilities.networkInfo();

this works, but if the connection drops or reconnects, it doesn't update the $scope.networkinfo. I can listen to the broadcast, but I would think I could drop the broadcast part

Upvotes: 0

Views: 131

Answers (1)

Pierre Gayvallet
Pierre Gayvallet

Reputation: 2953

You can simply watch the cskiwiUtilities.networkInfo() call to update the scope attribute when the value change :

$scope.$watch(function() {
    return cskiwiUtilities.networkInfo();
}, function(networkInfo) {
    $scope.networkInfo = networkInfo;
})

Depending on your needs and usages, you may also want the information to be accessible anywhere, by setting it on your $rootScope from your service :

 $rootScope.$watch('online', function(newStatus) {
     $rootScope.$broadcast('onlineUpdate', newStatus);
     $rootScope.networkInfo = newStatus;
 });

The 'networkInfo' props would then be accessible in any non-isolated part (scope) of your application.

Upvotes: 1

Related Questions