Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hai i am new in Angularjs. I am trying to read data from JSON file, But it returns a strange output. Here is my controller.js file

angular
.module('app')
.controller('homeCtrl',function($scope,Friend){
      $scope.friends=Friend.get();
      console.log("DATA FROM JSON:",$scope.friends);
      $scope.title="Home";       

})

Here is my services.js file

angular
.module('app')
.factory('Friend',function($http){

   return {
    get:function(){

            console.log("inside function");
            return [


            $http.get('/api/get.json').then(function(msg){

                return msg.data;    
            })
           ]          
        }
   }
})

console output is

DATA FROM JSON: 
[Object]
0: Object
length: 1
__proto__: Array[0

Please help.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

$http.get returns a promise and you're returning an array containing that promise.

Do this instead:

angular
.module('app.services', [])
.factory('Friend', function ($http) {
    return {
        get: function () {
            console.log("inside function");
            return $http.get('/api/get.json');
        }
    };
});

Then use your factory this way:

.angular
.module('app.controllers', ['app.services'])
.controller('yourCtrl', function ($scope, Friend) {
    Friend.get().then(function (msg) {
        $scope.msg = msg;
    });
});
share|improve this answer
    
It works fine when i change argument msg to msg.data,thanks bro. –  shammon Aug 22 '14 at 5:01
    
Can you give an answer for this? (stackoverflow.com/questions/25831459/…) –  shammon Sep 15 '14 at 10:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.