Doro Doro - 1 year ago 66
AngularJS Question

Using $http inside my own service - variable does not persist

I try to use a service to get some data from server, but I had a problem: even the console log out the length when I print 'myData.length', when I try to find length of '$scope.test' controller variable it tell me that it is undefined.

What I should to do to use a $http service inside my own service?

app.controller('mainCtrl', ['$scope', 'mapServ',
function($scope, mapServ) {
$scope.test = [];
$scope.test = mapServ.test;
console.log('$scope.test = ' + $scope.test.length);

app.factory('mapServ', ['$http', function ($http) {
var path = "file path to my server data";
var out = {};
var myData = [];
out.test = $http.get(path).then(function (response) {
myData =;
return out;

Answer Source

Take these service and controller as an example and you should follow John Papa's style guide while writing the code.


(function() {
            'use strict';

                .factory('appAjaxSvc', appAjaxSvc);

            appAjaxSvc.$inject = ['$http', '$q'];

            /* @ngInject */
            function appAjaxSvc($http, $q) {

                return {
                    getData:function (path){

                      //Create a promise using promise library
                        var deferred = $q.defer();

                            method: 'GET', 
                            url: "file path to my server data"
                        success(function(data, status, headers,config){
                        error(function(data, status, headers,config){

                        return deferred.promise;


    (function() {

            .controller('appCtrl', appCtrl);

        appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];

        /* @ngInject */
        function appCtrl($scope, $stateParams, appAjaxSvc) {
            var vm = this;
            vm.title = 'appCtrl';



            function activate() {

                appAjaxSvc.getData().then(function(response) {
                    //do something
                }, function(error) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download