AngularJS Custom Dropdown Time Filter

Sat, 27 Dec 2014

I've created this filter to allow hour selection using HTML dropdown.

The filter accepts as input three paramers: the starting hour, the ending hour, and the minute interval.

var app = angular.module('APP', ['APP.filters']);

app.controller('MainController', ['$scope', function($scope) {
 
}]);

angular.module('APP.filters', []).filter('time', function() {
    return function(input, from, to, interval) {
        from     = parseInt(from, 10);
        to       = parseInt(to, 10);
        interval = parseInt(interval, 10);

        for(var i=from, y=0; i<=to; ++i, y+=interval) {
            for(var y=0; y<60; y+=interval) {
                input.push(((i % 12) || 12)+ ":" + (y===0?'00':y) +" " + (i>12?'pm':'am'));
            }
        }
    
        return input;
    };
});

Usage:

<div ng-app="APP" ng-controller="MainController">
    <select>
        <option ng-repeat="h_m in [] | time:8:20:60">{{h_m}}</option>
    </select>
</div>

The above filter time:8:20:60 will output all the hours starting with 8 AM - 8 PM

8:00 am 8:15 am 8:30 am 8:45 am 9:00 am 9:15 am 9:30 am 9:45 am 10:00 am 10:15 am 10:30 am 10:45 am 11:00 am 11:15 am 11:30 am 11:45 am 12:00 am 12:15 am 12:30 am 12:45 am 1:00 pm 1:15 pm 1:30 pm 1:45 pm 2:00 pm 2:15 pm 2:30 pm 2:45 pm 3:00 pm 3:15 pm 3:30 pm 3:45 pm 4:00 pm 4:15 pm 4:30 pm 4:45 pm 5:00 pm 5:15 pm 5:30 pm 5:45 pm 6:00 pm 6:15 pm 6:30 pm 6:45 pm 7:00 pm 7:15 pm 7:30 pm 7:45 pm 8:00 pm 8:15 pm 8:30 pm 8:45 pm

The starting/ending hour must be between 0-24.

The interval can be between 1-60.

The filter can be used for showing multiple minutes in an hour.

For example time:10:14:15 will output 10:00 am, 10:15 am, 10:30 am, ... , 13:45 pm, 14:00 pm.

10:00 am 10:15 am 10:30 am 10:45 am 11:00 am 11:15 am 11:30 am 11:45 am 12:00 am 12:15 am 12:30 am 12:45 am 1:00 pm 1:15 pm 1:30 pm 1:45 pm 2:00 pm 2:15 pm 2:30 pm 2:45 pm

Categories: angularjs, javascript