在Angularjs中处理来自$ HTTP的返回对象

时间:2014-10-25 13:14:36

标签: angularjs date compare momentjs

我有一个包含很多项目的数据库,我需要抓住item.expire日期并将其与今天的日期进行比较所以我会在到期前5天回复"# 34。

我完成了所有工作,但我不知道如何通过我的号码 5 "在到期前5天#34; 我的ng-repeat。

 .controller('itemController', ['$scope', '$http', 'Items',
    function($scope, $http, Items) {

        var promise = Items.get();
        promise.then(
            function(itemData) {

                //Return data object to the ng-repeat
                $scope.items = itemData.data;


                angular.forEach(itemData.data, function(oneItem) {

                    var currentDate = moment().format("YYYY-MM-DD");
                    var a = moment(oneItem.expire);
                    var b = moment( currentDate );

                    $scope.items.expire = a.diff(b, 'days');
                });
            },
            function(errorItemData) {
                $log.error('failure loading item', errorItemData);
                console.log("error");
            });

我的HTML

 <tr ng-repeat="item in items | filter:searchItem" class="certificateListItems">


            <td> @{{ item.name }}</td>
            <td class="hidden-xs hidden-sm">@{{ item.description }}</td>
            <td class="hidden-xs hidden-sm">@{{ item.issuer }}</td>

            <td><a href="{{ URL::to('items/view_file/')  }}/@{{ item.id }} " target="_blank">Download</a></td>

            <td><img ng-click="showBox(item)" ng-src="{{ asset('assets/img/icons/mail_outgoing.png') }}"
                     alt="Send mail"/></td>
            <td>
                @{{ item.expire  }}
            </td>
            <td>1st: @{{ item.alarm1 | date : 'shortDate' }}<br>2nd: @{{ item.alarm2 | date : 'shortDate' }}</td>
            <td>
                <a ng-click="editItem(item)" href=""><span class="glyphicon glyphicon-pencil"></span></a> -
                <a ng-click="deleteItem(item)" href=""><span class="glyphicon glyphicon-trash"></span></a>
            </td>

        </tr>

1 个答案:

答案 0 :(得分:1)

每个项目都有自己的到期日期。但是你的循环将到期时间存储在一个变量中:

// $scope.items is an array of items.
$scope.items = itemData.data;

angular.forEach(itemData.data, function(oneItem) {

    var currentDate = moment().format("YYYY-MM-DD");
    var a = moment(oneItem.expire);
    var b = moment( currentDate );

    // this sets a property 'exire' on the array of data
    $scope.items.expire = a.diff(b, 'days');
});

应该是

$scope.items = itemData.data;

angular.forEach(itemData.data, function(oneItem) {

    var currentDate = moment().format("YYYY-MM-DD");
    var a = moment(oneItem.expire);
    var b = moment( currentDate );

    // this sets a property 'exire' on the array of data
    oneItem.daysBeforeExpiration = a.diff(b, 'days');
});

,在HTML中:

{{ item.daysBeforeExpiration }}