我尝试从json file获取数据。
这是JS代码:

var app = angular.module('ForecastApp', []);
console.log('in app');

//fetches weather data from service
  var res ="";
app.factory('forecast', ['$http', function($http) {

$http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json')
          .success(function(data) { console.log(data); res = data; })
          .error(function(err) { console.log(err); res = err;});
          return res;
}]);

//Save weather data into $scope.fiveDay
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
      $scope.fiveDay = res;
      console.log('in controller');
    }]);


然后我在主HTML文件中运行:

<body ng-app="ForecastApp">
    <div class="main" ng-controller="MainController">
      ...
            <h1>{{ fiveDay.city_name }}</h1>
...


fiveDay.city_name不返回任何内容,仅显示空白。 fiveDay应该具有res的值,这是一个对象,对吗?我不明白为什么fiveDay.city_name不是纽约。

最佳答案

我提供了一个简单的解决方案,仅在控制器中使用$ http Service



var app = angular.module('ForecastApp', []);
console.log('in app');


//Save weather data into $scope.fiveDay
app.controller('MainController', ['$scope', '$http', function($scope, $http) {
      $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json')
          .success(function(data) { console.log(data); $scope.fiveDay = data; })
          .error(function(err) { console.log(err);});

      console.log('in controller');
    }]);

<html>

  <head>
    <script data-require="[email protected]" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="ForecastApp">
    <div class="main" ng-controller="MainController">
      ...
            <h1>{{ fiveDay.city_name }}</h1>
            </div>
  </body>

</html>





见这里的朋克demo

07-28 11:18