harshk17
harshk17

Reputation: 120

Change the background color based on the time using angularjs.

I have written the code for it in which i try to convert the time into hex value and then pass that hex value to background-color. This is the code for the controller and below is the code for view. Any help is appreciated.I think i am missing something very small here but am not able to figure it out.

var app = angular.module('myApp', []);
app.controller('TimeCtrl', function($scope,$timeout, $filter) {
    $scope.clock = "loading clock"; // initialise the time variable
    $scope.tickInterval = 1000 //ms
    

    var tick = function () {
        $scope.clock = Date.now() // get the current time
        $scope.a = $filter('date')($scope.clock,'HHmmss');
        $timeout(tick, $scope.tickInterval); // reset the timer
    }

    // Start the timer
    $timeout(tick, $scope.tickInterval);
   
})
<html>

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller='TimeCtrl'>
      <p ng-style="{'background-color': '#{{a}}'}">{{clock |date : 'HH:mm:ss'}}</p>
        {{a}}
    </div>
  </body>

</html>

Upvotes: 0

Views: 2472

Answers (1)

First off, you don't want to use $timeout in this case, you want to use $interval

Second, ng-style already expects an angular expression, so there is no need for the {{}}. All I did was change the expression to be syntactically correct.

var app = angular.module('myApp', []);
app.controller('TimeCtrl', function($scope,$interval, $filter) {
    $scope.clock = "loading clock"; // initialise the time variable
    $scope.tickInterval = 1000 //ms

    var tick = function () {
        $scope.clock = Date.now() // get the current time
        $scope.a = $filter('date')($scope.clock,'HHmmss');
    }

    // Start the timer
    $interval(tick, $scope.tickInterval);
   
})
<html>

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller='TimeCtrl'>
      <p ng-style="{'background-color': '#' + a }">{{clock |date : 'HH:mm:ss'}}</p>
        {{a}}
    </div>
  </body>

</html>

Upvotes: 1

Related Questions