Markus Johansson
Markus Johansson

Reputation: 3773

How to use an expression which is based on time?

I have a button in my app, I only want it to be visible at night.

The javascript code:

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

And the html:

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

How can I make the expression be reevaluated when needed? Or is there a better approach for expressions depending on time?

Upvotes: 0

Views: 47

Answers (3)

masimplo
masimplo

Reputation: 3774

You could use an interval (preferably inside a directive) to check the time and set the visibility but you could also use a filter that is evaluated in every digest cycle.

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;
  }
});

And you can use them like:

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

Demonstrated at this plnkr http://plnkr.co/edit/tjAVWf

Upvotes: 2

Monkey Monk
Monkey Monk

Reputation: 990

I will assume that the "when needed" part is meaning "when the scope change".

So I propose using a filter like so:

HTML

<button ng-show="someDate | isNight">Visible at night</button>

or

<button ng-show="someDate | isNight:19:5">Visible at night</button>

Javascript

angular.module('yourApp', [])
.filter('isNight', IsNightFilter);

IsNightFilter.$inject = ['$filter'];

function IsNightFilter($filter) {
    return function (now, startNight, endNight) {
        if (now) {
            if (typeof now.getMonth !== 'function') {
                now = new Date(now);
            }

            var hours = now.getHours();

            startNight = startNight || 22;
            endNight = endNight || 6;

            if (hours < endNight || hours > startNight) {
                return true;
            }
        }

        return false;
    };
}

Upvotes: 0

bvaughn
bvaughn

Reputation: 13487

Maybe something like this?

var checkForNight = function() {
  var now = new Date();
  if (now.getHours() < 6 || now.getHours() > 22) {
    // It's night! Show your button!
    return true;
  }

  return false;
};

if (!checkForNight()) {
  var checkForNightIntervalID = setInterval(function() {
    if (checkForNight()) {
      clearInterval(checkForNightIntervalID);
    }
  }, 60000 /* check once per minute */);
}

Edit for better clarity.

Upvotes: 0

Related Questions