2014-04-16 14 views
3

您好我有一個這樣的代碼在我的控制器解析JSON字符串在AngularJS - 給出不確定

myClientApp.controller('ListCtrl', function ($scope,$http,$cookieStore,$location, $routeParams) { 
var data = { 
      "menus": { 
       "view": true, 
       "add": true, 
       "update": true, 
       "delete": true 
       }, 
       "linkInfo": { 
       "labelColumn": "codeName", 
       "linkColumn": "lookupKey", 
       "urlInfo": "reference" 
       }, 
       "resultList": [ 
       "{\"lookupKey\":2,\"clientKey\":1,\"codeName\":\"Application.AppType\",\"codeValue\":\"ApplicationType2\",\"codeDesc\":\"##\",\"updatedBy\":null,\"internalCodeName\":\"Application.AppType\"}", 
       "{\"lookupKey\":3,\"clientKey\":1,\"codeName\":\"Application.Class\",\"codeValue\":\"Tier 1\",\"codeDesc\":\"Critical Application requiring immediate response in case of a disruption of Service\",\"updatedBy\":null,\"internalCodeName\":\"Application.Class\"}" 
       ] 
      }; 
    $scope.result = angular.fromJson(data.resultList); 
    alert($scope.result[0].codeName); 
}); 

以下,這讓我不確定。爲什麼?

+0

你試過'$ scope.result = angular.fromJson(data.resultList [0]);'然後'警報($ scope.result.codeName );'? – Satpal

+0

OH。所以我們必須遍歷每個對象? – iCode

+1

Yep隊友使用一個簡單的循環 – Satpal

回答

13

因爲​​是JSON字符串數組,而不是單個JSON字符串;你需要指定要解碼其中的關鍵:

$scope.result = [ 
    angular.fromJson(data.resultList[0]), 
    angular.fromJson(data.resultList[1]) 
]; 
alert($scope.result[0].codeName); 
+0

我會建議將這個變成你自己的服務,所以它可以在測試時被模擬出來。除非有一個有角度的方法來做到這一點? –

+0

感謝朋友! –