javascriptangularjsangularjs-ng-show

AngularJS ng-show not working with my function defined in a factory


I am using the angular ng-show directive to check if a user is an admin user and if they are then I want certain html elements to be "shown".

I firstly created the following function called checkIfUserIsAdmin in my mainController:

 $scope.checkIfUserIsAdmin = function(){
        var userPrivilegeID = sharedFactory.userDetails.userPrivilegeID; 
        if(userPrivilegeID === 2){
            return true;
        }else{
            return false;
        }
    }

and in my html I had the following:

<span ng-show="checkIfUserIsAdmin()"><i class="fa fa-check-circle"></i></span>

It was working well with ng-show and the html was changing as planned when the userPrivilegeID changed value.

However I decided I want to define this function in a factory instead so that I can pass it to multiple controllers.

However now when the userPrivilegeID changes the view does not update (as it should with ng-show). Apologies if it's a silly mistake but i've been trying to figure it out a while now and haven't found anything online. Can you help please?

sharedFactory.js

//create a factory so that we can pass these variables between different controllers. 
myApp.factory('sharedFactory', function(){
    //private variables
    var userDetails = {   
        "userID" : null,
        "userPrivilegeID" : 1,
        "isLoggedIn" : false
    }; 
    var checkIfUserIsAdmin = function(){
        var userPrivilegeID = userDetails.userPrivilegeID; 
        if(userPrivilegeID === 2){
            return true;
        }else{
            return false;
        }
    };

    //return public API so that we can access it in all controllers
    return{
        userDetails: userDetails,
        checkIfUserIsAdmin: checkIfUserIsAdmin
    };
});

mainController.js

 myApp.controller("mainController", function($scope, sharedFactory){
        $scope.checkIfUserIsAdmin = function(){
            return sharedFactory.checkIfUserIsAdmin; 
        }  
    });

index.html file (the most relevant parts for this question)

 <body data-ng-controller="mainController">
        <div id="container_wrapper">
            <div class="container"> 
                <span ng-show="checkIfUserIsAdmin()"><i class="fa fa-check-circle"></i></span>
                <div ng-view>
                    <!--our individual views will be displayed here-->
                </div>
            </div>
        </div>
    </body>

Edit: The userPrivilegeID is initialized to 1 as you can see above. However after I do an API call It is then set to 2 however ng-show is not updating to display the html. Here is my loginFactory which contains the API call

myApp.factory('loginFactory', function($http, $timeout, $q, sharedFactory){

    //Methods which perform API calls 
    var checkLoginDetails = function(data){
        var deferred = $q.defer();
        $http({
            method: 'POST',
            url: 'http://localhost/API/auth?apiKey=0417883d',
            data : JSON.stringify(data),
            headers: {
               'Content-Type': 'application/json;charset=utf-8'
            },
            responseType:'json'
        }).then(function successCallback(response){

            if(response.hasOwnProperty('data') && response.data !== null){
                console.log(JSON.stringify(response.data));
                sharedFactory.userDetails = {
                   "userID" : response.data.userID,
                   "userPrivilegeID" : response.data.userPrivilegeID, 
                   "isLoggedIn" : true
                };

                $timeout(function() {
                    deferred.resolve(sharedFactory.userDetails);
                }, 100);
            }else{
                sharedFactory.buildErrorNotification(response);

            }
        },function errorCallback(response){
            sharedFactory.buildErrorNotification(response);

        });
        //return the userDetails promise
        return deferred.promise;
    };


    //return public API so that we can access it in all controllers
    return{
        checkLoginDetails: checkLoginDetails
    };
});

And then in my mainController I have the following (which calls the checkLoginDetails function):

$scope.loginWithFacebook = function(){

    var data = {//...
    };

    loginFactory.checkLoginDetails(data).then(function(userDetails) {
        //Since the checkLoginDetails method (in the loginFactory) is performing a http request we need to use a promise
        //to store the userDetails (from the response) into our $scope.userDetails variable. 
        $scope.userDetails = userDetails;
    });

}  

Solution

  • You left off the parens on the call to your service function.

     myApp.controller("mainController", function($scope, sharedFactory){
            $scope.checkIfUserIsAdmin = function(){
                return sharedFactory.checkIfUserIsAdmin(); //<-- Needs to actually call the function.
            }  
        });
    

    Change your service to something like this:

    //create a factory so that we can pass these variables between different controllers. 
    myApp.factory('sharedFactory', function(){
        //private variables
    
        var service = {
            userDetails: {   
                "userID" : null,
                "userPrivilegeID" : 1,
                "isLoggedIn" : false
            }
        };
    
        service.checkIfUserIsAdmin = function (){
            var userPrivilegeID = service.userDetails.userPrivilegeID; 
            if(userPrivilegeID === 2){
                return true;
            }else{
                return false;
            }
        };
    
        //return public API so that we can access it in all controllers
        return service;
    });