2013-11-26 45 views
1

我是angularjs的初學者,對web服務也沒有任何想法。我的要求是這樣的:

我得從我的網址,以獲取一個JSON對象http://mylocalhostname.dev/users/list?city_id=12

我絕對無能......請幫我修改我的代碼。

在此先感謝。這裏是我的JS代碼:

'use strict'; 

var services = angular.module('services', ['ngResource']); 

services.factory('dataFactory', ['$resource','$http', '$log', 
     function ($resource, $http, $log) { 
       return { 
        getAllUsers: function(){ 
         return $resource('http://mylocalhostname.dev/users/list',{city_id:12} 
          ,{ 
           locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter) 
            $log.info(data.UsersList[0]); 
            return data.UsersList[0].userName; 
           })} 
          } 
         ); 
        } 
       } 
    }]); 

當我測試我得到了我的控制檯此消息:

GET http://mylocalhostname.dev/users/list?city_id=12 200 OK 164ms angular.js(LIGNE 7772) (在紅色) (空字符串)

回答

2

(我知道這是一個古老的問題,但仍然沒有答案,它出現在搜索我只是做的頂部,所以希望這可以關閉特定的循環)

一個反面的簡單例子troller從一個簡單的工廠檢索數據,工廠使用$ resource訪問本地託管文件並將文件內容返回給控制器。

工廠:

'use strict'; 
angular.module('myApp') 
    .factory('myFactory', ['$resource', function($resource) { 
    return function(fileName){ 
     return $resource(fileName, {}); 
    }; 
    }]); 

控制器:

'use strict'; 
var fileToGet = 'some/path/to/file.json'; 
angular.module('myApp') 
    .controller('myController', function($scope, myFactory) { 
    var getDefs = new myFactory(fileToGet).get(function(data) { 
     $scope.wholeFile = data; 
     // $scope.wholeFile should contain the entire JSON-formatted object 

     $scope.someSection = data.section; 
     // $scope.someSection should contain the "varX" and "varY" items now 

     $scope.myStringX = JSON.stringify(data.section.varX); 
     // get the stringified value 
    }); 
}); 

的JSON格式的文件:

{ 
    "someVar": "xyz", 
    "someArray": [ 
    { 
     "element0A": "foo", 
     "element0B": "bar" 
    }, 
    { 
     "element1A": "man", 
     "element1B": "chu" 
    } 
    ], 
    "section": { 
    "varX": 0, 
    "varY": "yyyy" 
    } 
} 
+0

tinks,現在的工作:) –

相關問題