Search code examples
angularjsangularjs-controllerangularjs-factoryangularjs-http

AngularJS - Factory from Controller - not getting value from $http.get


I have a newbie question here.

I am coding a factory in angularJS. With it I want to have a list of users, and also a method to fill it.

So this is my code ...

The factory

app.factory("usuariosFactory", function ($http) {


    var f = {};

    f.users = [];

    f.getUsers = function (callback) {
        var token = window.localStorage.getItem("_token");


        $http.get("http://localhost:8000/api/user/list?token=" + token).then(function (response) {
            f.users = response.data.users;

            /* the console.log outputs OK with the users from the server */
            console.log(f.users);
        });
    }; 

    return f;
});

The controller

app.controller("usuariosController", function ($scope, usuariosFactory) {
    var scope = this;

    /* link users from factory to controllerś scope .. NOT WORKING */
    usuariosFactory.getUsers();

    scope.usuarios = usuariosFactory.users;
});

I am hitting my head to the desk right now. I dont understand how to achieve this.


Solution

  • You should just return the promise from the factory to controller

    Then in controller, you should subscribe to that promise and assign data to your scope variable

    Factory:

    app.factory("usuariosFactory", function ($http) {
        var f = {};
        f.users = [];
        f.getUsers = function (callback) {
            var token = window.localStorage.getItem("_token");
            return $http.get("http://localhost:8000/api/user/list?token=" + token);
        };
        return f;
    });
    

    Controller:

    app.controller("usuariosController", function ($scope, usuariosFactory) {
        var scope = this;
        usuariosFactory.getUsers().then(function (response) {
            scope.usuarios = response.data;
        });
    });