Angular:如何在控制器中循环JSON并在视图中显示

时间:2015-06-12 17:30:54

标签: javascript jquery arrays json angularjs

我正在学习Angular而且我遇到了一项任务。我的应用程序中有三个部分:视图,服务和控制器, 查看如下:

<body ng-app="ForecastApp">

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">

          <p class="navbar-brand">Week Forecast</p>

      </div>
    </nav>

    <div class="container-fluid"  class="main" ng-controller="MainController">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <h2><span class="label label-info">Search for a City</span></h2>
          <div class="input-group">

            <input type="text" class="form-control" placeholder="City name...">
              <span class="input-group-btn">
            <button class="btn btn-default" type="button">Go!</button>
          </span>
          </div>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h1 class="page-header">{{ fiveDay.city.name }}</h1>

          <div class="forecast" ng-repeat="day in fiveDay.days">

              </div>
              </div>

        </div>
      </div>
    </div>
</body>

服务看起来像这样:

app.factory('forecast', ['$http', function($http) { 
  return $http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=Warsaw&units=metric&mo') 
            .success(function(data) { 
              return data; 
            }) 
            .error(function(err) { 
              return err; 
            }); 
}]);

控制器看起来像这样:

app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {

  forecast.success(function(data) { 
    $scope.fiveDay = data; 
  });

}]);

本课程的数据来自此处的其余API http://api.openweathermap.org/data/2.5/forecast/city?q=Warsaw&units=metric&mo

如何抛出所有这些json resposne并显示来自此json的数组“list”中的所有项目,例如如下所示:

日期:“2015-06-12 15:00:00” 描述:“少云” 温度:26.82 压力:1015.2

1 个答案:

答案 0 :(得分:2)

当我看到它简单的JSON时,您可以使用.&amp;只要有需要,请提及index来获取值。

<强>代码

$scope.fiveDays = data.list

<强>标记

<div class="forecast" ng-repeat="day in fiveDays ">
   <div>Date : {{dt|date: 'yyyy-dd-MM'}}</div>
   <div>description: {{weather[0].description}}</div>
   <div>temp: {{main.temp}}</div>
   <div>pressure: {{main.pressure}}</div>
</div>

不同的angular date filter format