以 ng 样式获取当前日期 - Angularjs

get current date in ng-style - Angularjs

本文关键字:Angularjs 当前日期 获取 ng 样式      更新时间:2023-09-26

在我的角度应用程序中,如果日期等于今天,我需要表格行的背景颜色为红色。

到目前为止,我设法仅在等于"2016-01-31"时才设置红色,

如果"2016-01-31"是当前日期,我该如何使其工作?

        <tbody>
            <tr ng-repeat="issue in data.issues|orderBy:orderByField:reverseSort" ng-style="{'background-color': issue.due_date == '2016-01-31' ?  'red': 'white'}" ng-click="setSelected()">
                <td>{{issue.id}}</td>
                <td>{{issue.project.name}}</td>
                <td>{{issue.subject}}</td>
                <td>{{issue.start_date}}</td>
                <td>{{issue.due_date}}</td>
                <td>{{issue.priority.name}}</td>
            </tr>
        </tbody>

使用函数来定义你的值是否为今天

   <tbody ng-controller="MyCtrl">
        <tr ng-repeat="issue in data.issues|orderBy:orderByField:reverseSort" ng-style="{'background-color': isToday(issue.due_date) ?  'red': 'white'}" ng-click="setSelected()">
            <td>{{issue.id}}</td>
            <td>{{issue.project.name}}</td>
            <td>{{issue.subject}}</td>
            <td>{{issue.start_date}}</td>
            <td>{{issue.due_date}}</td>
            <td>{{issue.priority.name}}</td>
        </tr>
    </tbody>

并在应用中定义此函数

.controller('MyCtrl', function($scope){
    $scope.today = new Date();
    $scope.isToday = function(compareDate){
       var today = $scope.today;
       return compareDate == today.getFullYear() + '-' + today.getDate() + '-' + today.getMonth();
    }
})

我还建议使用类而不是内联样式,有关更多信息,请参阅ng-class

您可以在作用域中创建一个局部变量,如下所示

$scope.currentDate = new Date();

然后

ng-style="{'background-color': issue.due_date == currentDate ?  'red': 'white'}

我认为日期格式在due_date和当前日期中应该保持一致,所以请确保它们是一致的。

希望这有帮助。