Angular - 获取天数以获取天气信息

时间:2016-07-31 18:25:32

标签: angularjs json

我想从数据天气Json得到一周中的几天,我正在使用此代码 “

 var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    var date = new Date();
$scope.wDay = dayNames[date.getDay()];

html

{{wDay}}

结果只有一天'太阳'而不是一周的所有日子

完整的json数据

 {

  "daily": {
    "summary": "لا أمطار خلال الأسبوع مع درجات حرارة ترتفع حتى 50°C يوم الأربعاء",
    "icon": "clear-day",
    "data": [
      {
        "time": 1469912400,
        "summary": "اجواء جافة خلال اليوم",
        "icon": "clear-day",
        "sunriseTime": 1469931375,
        "sunsetTime": 1469981058,
        "moonPhase": 0.91,
        "precipIntensity": 0,
        "precipIntensityMax": 0,
        "precipProbability": 0,
        "temperatureMin": 30.7,
        "temperatureMinTime": 1469930400,

      },

2 个答案:

答案 0 :(得分:0)

此程序取决于时间。

new Date().getDay()

今天总会让你回归

答案 1 :(得分:0)

你只会看到周日 - 因为它是你专门为它测试的: dayNames - 与给定日期的星期几相对应的数字。

如果你想要所有这些,只需ng-repeat var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; var date = new Date(); function MyCtrl($scope) { $scope.today = dayNames[date.getDay()]; $scope.all = dayNames; } Today is {{today}}! <div ng-repeat="day in all"> {{day}} </div>

//Added a filter to grab today's data from JSON
myApp.filter('GetToday',function(){
  return function(epoch) {

    //Get today
    var today = moment();

    //Loop through all the daily nodes from the JSON
    for (var i = 0; i < epoch.length; i++) {

        //convert UNIX timestamp to date
        var json = moment.unix(epoch[i].time); 

        //determine difference between dates
        var duration = moment.duration(json.diff(today));

        //convert the difference into hours
        var hours = duration.asHours();

        //if it's more than 0 and less than 24 (today) return this node
        if(hours > 0 && hours < 24) {
            return epoch[i];
        }
    }
  }
});

myApp.controller('MyCtrl', ['$scope', '$filter', function($scope, $filter){
        $scope.daily = $filter('GetToday')(data[0].daily.data);
}]);

http://jsfiddle.net/Lvc0u55v/7751/

修改的: 改变问题的范围,所以这里是答案的补充。它当然可以用更简洁的方式编写,但为了简洁而扩展:

http://jsfiddle.net/Lvc0u55v/7896/

我添加了MomentJS(http://momentjs.com) - 非常适合处理日期。

{{1}}