0

I am making authentication for my app and I've been struggling with getting a service to work properly. I have simplified the code.

The service:

App.factory('AuthenticationService', function() {
    var isLoggedIn = false;

    return {
        isLoggedIn : function() {
            return isLoggedIn;
        }
    }
});

MainController:

App.controller('MainController', [
    '$scope',
    'AuthenticationService',
    function( $scope, AuthenticationService ) {

        $scope.isLoggedIn = AuthenticationService.isLoggedIn();

        $scope.$watch('AuthenticationService.isLoggedIn()', function (newVal, oldVal) {
            console.log("Detected change in service.");
            if( newVal !== oldVal ) {
                $scope.isLoggedIn = newVal;
            }
        });
    }]);

LoginController:

// Login HTTP request successful, returns a positive answer
// Now I want to change the variable in the service to True

AuthenticationService.isLoggedIn = true;

Main problem: The way the service variable is modified from LoginController right now - it is not reflected in the watcher and I am not sure if it even changes the variable in the service. What is wrong there?

The goal: Instant change in the view after a successful login (ng-show).

Any other constructive criticism towards the code is welcome.

Markus Pint
  • 348
  • 3
  • 17
  • Is this approach in particular important to you? I know of two options: observers within the service and a broadcast. I typically use a broadcast. Code examples are on the top answer to this question but I can also put something together for you with your code: http://stackoverflow.com/questions/12576798/angularjs-how-to-watch-service-variables – Jennifer Gilbert Aug 17 '14 at 20:00
  • Yes, because I have seen many tutorials using this approach, but cannot get it to work for some reason. – Markus Pint Aug 17 '14 at 20:12

1 Answers1

1

There are several ways.

1) Use broadcast events
2) Create a scope for your service:

App.factory('AuthenticationService', function($rootScope) {
    var isLoggedIn = false;
    var AuthenticationService = $rootScope.$new();
    return AuthenticationService;
});

3) You could watch a property:

App.factory('AuthenticationService', function() {
    return {
        isLoggedIn : false
    }
});

// In your controller:
 $scope.$watch('AuthenticationService.isLoggedIn', function(){...

4) You could write a custom watcher:

App.factory('AuthenticationService', function() {
    var isLoggedIn = false;

    return {
        isLoggedIn : function() {
            return isLoggedIn;
        }
    }
});

// In your controller
$scope.$watch(function(){return AuthenticationService.isLoggedIn()}, function(){...
jantimon
  • 36,840
  • 23
  • 122
  • 185