繁体   English   中英

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

[英]Change the background color based on the time using angularjs.

我已经为其编写了代码,其中我尝试将时间转换为十六进制值,然后将该十六进制值传递给background-color。 这是控制器的代码,下面是用于查看的代码。 感谢任何帮助。我想我在这里错过了一些很小的东西,但无法弄清楚。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM