AngularJS - 来自JSON字符串的数据绑定

时间:2014-07-27 02:05:52

标签: javascript json angularjs

我对AngularJS全新,并尝试从SOAP Web服务捕获,解析和显示数据。到目前为止,我可以调用成功调用公共天气服务,捕获并显示返回的XML数据,将XML转换为JSON字符串,但我没有成功绑定/显示JSON数据。下面是我的HTML和JS文件。提前感谢任何意见/建议!

MyHelloView.html

<!doctype html>
<html>
<head>
<script language="JavaScript" type="text/JavaScript" src="angular.min.js"> </script>
<script language="JavaScript" type="text/JavaScript" src="xml2json.js"></script>
<script language="JavaScript" type="text/JavaScript" src="MyHelloController.js">    </script>
</head>
<body ng-app>
<title>My Simple Angular App</title>

<div ng-controller='MyHttpController'>
{{soapResponse}} 
<br/><br/>
{{jsonData}}
<br/><br/>
WeatherReturn: <br/>
Success:        <input type="text" ng-model="jsonData.Success" /> <br/>
ResponseText:   <input type="text" ng-model="jsonData.ResponseText" /> <br/>
State:          <input type="text" ng-model="jsonData.State" /> <br/>
City:           <input type="text" ng-model="jsonData.City" /> <br/>
WeatherStationCity: <input type="text" ng-model="jsonString.WeatherStationCity" /> <br/>
WeatherID:      <input type="text" ng-model="jsonData.WeatherID" /> <br/>
Description:    <input type="text" ng-model="jsonData.Description" /> <br/>
Temperature:    <input type="text" ng-model="jsonData.Temperature" /> <br/>
RelativeHumidity: <input type="text" ng-model="jsonData.RelativeHumidity" /> <br/>

<div ng-repeat="field in jsonData.fields">
      {{field.name}}: <input type="text" ng-model="field.value">
</div>
  <br/><br/>  
</div> 
</body>
</html>

MyHelloController.js

function MyHttpController($scope, $http) {
  $scope.loaded = false;
  $scope.soapResponse = 'no response yet';

  $http.get('http://wsf.cdyne.com//WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=60301').then(function(result){
  $scope.soapResponse = result.data;
  var x2js = new X2JS();            // convert XML data to JSON
  $scope.jsonData = x2js.xml_str2json(result.data);
  $scope.loaded = true;
  });
}

1 个答案:

答案 0 :(得分:0)

您的xml如下所示,这意味着您只需要从json对象的顶部提取数据。撇开,您可能会想要将控制器放在模块上并将天气变成服务......但您没有问过这个问题。

$scope.jsonData = x2js.xml_str2json(result.data).WeatherReturn;

<WeatherReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://ws.cdyne.com/WeatherWS/">
    <Success>true</Success>
    <ResponseText>City Found</ResponseText>
    <State>IL</State>
    <City>Oak Park</City>
    <WeatherStationCity>Maywood</WeatherStationCity>
    <WeatherID>14</WeatherID>
    <Description>Cloudy</Description>
    <Temperature>27</Temperature>
    <RelativeHumidity>63</RelativeHumidity>
    <Wind>S9</Wind>
    <Pressure>29.95F</Pressure>
    <Visibility/>
    <WindChill/>
    <Remarks/>
</WeatherReturn>