Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

javascript - Reading data from JSON file in Angularjs

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$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;
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...