gpt4 book ai didi

javascript - 如何使用基于时间的表达式?

转载 作者:行者123 更新时间:2023-12-02 16:24:10 26 4
gpt4 key购买 nike

我的应用程序中有一个按钮,我只希望它在夜间可见。

JavaScript 代码:

$scope.isNight = function() {
var now = new Date();
return now.getHours() < 6 || now.getHours() > 22;
};

和 html:

<button ng-show="isNight()">Visible at night</button>

如何在需要时重新评估表达式?或者有更好的根据时间表达的方法吗?

最佳答案

您可以使用间隔(最好在指令内)来检查时间并设置可见性,但您也可以使用在每个摘要周期中评估的过滤器。

app.directive('hideMeAtNight', function($interval) {
return {
restrict: "A",
link: function(scope, element, attributes) {
$interval(function() {
var now = new Date();
element.toggleClass('ng-hide', now.getHours() < 6 || now.getHours() > 22);
}, 1000)
}
};
});

app.filter('nightFilter', function() {
return function() {
var now = new Date();
return now.getHours() < 6 || now.getHours() > 22;
}
});

你可以像这样使用它们:

<button hide-me-at-night>This is a button</button>
<button ng-hide="true|nightFilter">This is a button</button>

在此 plnkr 上演示 http://plnkr.co/edit/tjAVWf

关于javascript - 如何使用基于时间的表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28842704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com