Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jcmargentina's avatar

AngularJS - Factory array from controller

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 having troubles getting this to work

0 likes
2 replies
nolros's avatar

@jcmargentina

The User API could be extracted to UserServices and ApiServices, but if I were actually writing an app I would build an APIProvider. If I were building a large app I would break it into Ap provideri, Http Endpoints, request service, url resolver, etc. services. However, to simplify here is an example

I have not tested or run the code, but here is how I would do it

  1. Blade example
<div class="article__col column--50"
     ng-controller="UserController as UserCtrl">
    <ul>
        <li ng-click="UserCtrl.setActive(user,$event)"
            ng-repeat="user in UserCtrl.data.users.data track by user.id">
                <p ng-bind="user.first_name"></p>
        </li>
    </ul>
</div>
  1. AngularJS example.
(function () {
    'use strict';


    UsersApi.$inject = ['$http', "$q", "_ROUTES", "$window"];
    function UsersApi($http,$q, _ROUTES, $window) {
        var service = this,
            token = $window.localStorage["_token"] || defaultValue;

        /**
         * API Resource instance. Needed if grow API to include http endpoints etc.
         */
        function Resource(resource) {
            this.resource = resource;
        }

        /**
         * api service as you will need api.get, api.save, etc
         */
        let api = function apiService(resource) {
            return new Resource(resource);
        };

        /**
         * Get on a given url
         *
         * @param url
         * @param params
         */
        api.get = function apiGet(url, params) {
            return http({
                method: 'GET',
                url: url,
                params: params // check for params
            });
        };

        function isOK(response) {
            function isErrData(data) {
                return data && data._status && data._status === 'ERR';
            }
            return response.status >= 200 && response.status < 300 && !isErrData(response.data);
        }


        /**
         * Call $http once url is resolved
         */
        function http(config) {
            return $q.when(config.url)
                .then(function(url) {
                    config.url = url;
                    return $http(config);
                }).then(function(response) {
                    return isOK(response) ? response.data : $q.reject(response);
                });
        }

        function hasUserRoute(url) {
            // can do further validation regex or string etc
            return (angular.isUndefined(url) ?_ROUTES.USERS : url) + token;
        }

        /**
         *Get all users of api url
         */
        service._getUsers = function (url, params = {}) {
            return api.get(hasUserRoute(url), params)
                .then(function (result) {
                    return result;
                });
        };

        return {
            getUsers: function (url, params) {
                return service._getUsers(url, params);
            }

        }
    }

    UserController.$inject = ['$scope','UsersApi'];
    function UserController($scope,UsersApi) {
        let vm = this,
  
            getAllUsers = function () {
                UsersApi
                    .getUsers()
                    .then(function (results) {
                        // you would do data and error validation here as well. For brevity sake ill let you handle
            // this is now used in blade or html
                        vm.data = {
                            users: results,
                        };
                    });
            };



        vm.$onInit = function () {
         // note: not good practice because there is no url or params being passed but just an example. The right way would be based on a method you would resolve url to a server and return the url to pass through to http method, but lets use as example

            getAllUsers();
        };
    }


    angular.module('myapp')
        .factory('UsersApi', UsersApi)
        .controller('UserController', UserController)
        .constant("_ROUTES", {
            USERS: 'http://localhost:8000/api/user/list?token=',
        })

})();
jcmargentina's avatar

@nolros , I am still reading your code ... I am a newbie still in angularJS that is why is taking me a while to understand your code.

after I ready and understand everything I will give you a reply.

But ... thanks a lot for your effort writting this piece of code.

Please or to participate in this conversation.