使用angularjs根据时间更改背景颜色

Change the background color based on the time using angularjs.

本文关键字:背景 颜色 时间 angularjs 使用      更新时间:2023-09-26

我已经为它编写了代码,其中我尝试将时间转换为十六进制值,然后将该十六进制值传递给背景色。这是控制器的代码,下面是视图的代码。感谢您的帮助。我想我在这里错过了一些很小的东西,但我无法弄清楚。

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>

首先,在这种情况下,您不想使用$timeout,而是希望使用$interval

其次,ng-style已经期望角度表达式,因此不需要{{}}。我所做的只是把这个表达改成语法正确。

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>