2013-07-23 24 views
4

我希望能夠使用ng-repeat來解析我在前端的響應。我無法使用ng-repeat列表分析具有多個項目與單個項目的響應。如何在Angularjs中正確解析JSON響應到ng-repeat

我能夠解析;但是我必須在前端創建2個不同的列表並單獨配置ng-repeat配置,並添加一些醜陋的邏輯,以便在數組長度大於1時不顯示。

我的目標是在我的部分中只有一個ng-repeat元素,並且它處理這兩個響應或處理此需求的更好方法。

詳細解釋和下面的jsfiddle。
我想爲這兩個JSON響應使用此ng-repeat設置。

<ul ng:repeat="report in reportConfigured.Reports"> 
    <li ng:repeat="reportItem in report">{{reportItem.ReportName.$}}</li> 
    </ul> 

下面是我有多個報告時從web服務獲得的響應。

{ 
    "Reports": { 
     "@xmlns": { 
      "$": "http:\/\/ws.wso2.org\/dataservice" 
     }, 
      "Report": [{ 
      "ReportID": { 
       "$": "20" 
      }, 
       "ReportName": { 
       "@xmlns": { 
        "$": "null" 
       }, 
        "$": "Examination Results" 
      }, 
       "VisibleToPartner": { 
       "$": "false" 
      }, 
       "ReportType": { 
       "@xmlns": { 
        "$": "null" 
       }, 
        "$": "Examination Report" 
      }, 
       "TemplateID": { 
       "$": "9" 
      } 
     }, { 
      "ReportID": { 
       "$": "163" 
      }, 
       "ReportName": { 
       "@xmlns": { 
        "$": "null" 
       }, 
        "$": "Scheduled Candidates with Test Center" 
      }, 
       "VisibleToPartner": { 
       "$": "false" 
      }, 
       "ReportType": { 
       "@xmlns": { 
        "$": "null" 
       }, 
        "$": "Examination Report" 
      }, 
       "TemplateID": { 
       "$": "220" 
      } 
     }, { 
      "ReportID": { 
       "$": "212" 
      }, 
       "ReportName": { 
       "@xmlns": { 
        "$": "null" 
       }, 
        "$": "Survey Report by Test" 
      }, 
       "VisibleToPartner": { 
       "$": "false" 
      }, 
       "ReportType": { 
       "@xmlns": { 
        "$": "null" 
       }, 
        "$": "Examination Report" 
      }, 
       "TemplateID": { 
       "$": "269" 
      } 
     }] 
    } 
}; 

我從我的服務這種反應時,只有一個報告

{ 
    "Reports": { 
     "@xmlns": { 
      "$": "http:\/\/ws.wso2.org\/dataservice" 
     }, 
     "Report": { 
      "ReportID": { 
       "$": "212" 
      }, 
      "ReportName": { 
       "@xmlns": { 
        "$": "null" 
       }, 
       "$": "Survey Report by Test" 
      }, 
      "VisibleToPartner": { 
       "$": "true" 
      }, 
      "ReportType": { 
       "@xmlns": { 
        "$": "null" 
       }, 
       "$": "Examination Report" 
      }, 
      "TemplateID": { 
       "$": "269" 
      } 
     } 
    } 
} 

我希望能夠用相同的ng-repeat解析兩種反應。我已經附加了一個jsfiddle瞭解更多細節。

http://jsfiddle.net/cejohnson/mdec9/1/

回答

10

我將改變你從服務器得到什麼它設置爲ng-repeat數據源之前:

$http({...}) 
.success(function(data){ 
    if (angular.isArray(data.Reports.Report)) { 
     $scope.reports = data.Reports.Report; 
    } 
    else { 
     $scope.reports = [data.Reports.Report]; 
    } 
}); 

然後

<ul ng:repeat="report in reports"> 
    <li ng:repeat="reportItem in report">{{reportItem.ReportName.$}}</li> 
</ul>