Angular JS Magazine

duminică, 14 septembrie 2014

Creating a Custom Clock

This tip shows you how to create different kind of clocks using Angular JS filters:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../angular/angular.min.js"></script>
    <style type="text/css">
        i {
            padding: 5px;
            font-size: 20px;
            color: #245269;
            display: block;
            font-family: Consolas;
        }
    </style>
    <script>
        angular.module("appModule", [])
                .controller("clockCtrl", function ($scope) {
                    $scope.clock = new Date();

                    var updateClock = function () {
                        $scope.clock = new Date();
                    };

                    setInterval(function () {
                        $scope.$apply(updateClock);
                    }, 1000);
                    updateClock();
                });
    </script>
</head>
<body>
<div ng-app="appModule" ng-controller="clockCtrl">
    Custom clock 1 (shortTime filter): <i>{{ clock | date:'shortTime' }}</i>
    Custom clock 2 (mediumTime filter): <i>{{ clock | date: 'mediumTime' }}</i>
    Custom clock 3 (short filter): <i>{{ clock | date: 'short' }}</i>
    Custom clock 4 (medium filter): <i>{{ clock | date: 'medium' }}</i>
</div>
</body>
</html>

Output:

Hours, minutes and seconds can be formatted as in figure below (source of this image: ng-book, by Ari Lerner):