Search code examples
javascriptangularjsangularjs-serviceangularjs-controller

AngularJS call common controller function from outside controller


My basic premise is I want to call back to the server to get the logged in user in case someone comes to the site and is still logged in. On the page I want to call this method. Since I am passing the user service to all my controllers I don't know which controller will be in use since I won't know what page they're landing on.

I have the following User Service

app.factory('userService', function ($window) {
    var root = {};
    root.get_current_user = function(http){
        var config = {
        params: {}
    };
    http.post("/api/user/show", null, config)
        .success(function(data, status, headers, config) {
            if(data.success == true) {
                user = data.user;

                show_authenticated();
            }

        });
    };
    return root;
});

Here is an empty controller I'm trying to inject the service into

app.controller('myResourcesController', function($scope, $http, userService) {

});

So on the top of my index file I want to have something along the lines of

controller.get_current_user();

This will be called from all the pages though so I'm not sure the syntax here. All examples I found related to calling a specific controller, and usually from within another controller. Perhaps this needs to go into my angularjs somewhere and not simply within a script tag on my index page.


Solution

  • You could run factory initialization in run method of your angular application. https://docs.angularjs.org/guide/module#module-loading-dependencies E.g.

    app.run(['userService', function(userService) {
      userService.get_current_user();
    }]);
    

    And userService factory should store authenticated user object internaly.

    ...
    if (data.success == true) {
      root.user = data.user;
    }
    ...
    

    Then you will be able to use your factory in any controller

    app.controller('myController', ['userService', function(userService) {
       //alert(userService.user);
    }]);