简体   繁体   English

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

[英]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. 我已经为其编写了代码,其中我尝试将时间转换为十六进制值,然后将该十六进制值传递给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> 

First off, you don't want to use $timeout in this case, you want to use $interval 首先,在这种情况下,您不想使用$timeout ,而您想使用$interval

Second, ng-style already expects an angular expression, so there is no need for the {{}} . 其次, ng-style已经期望有一个角度表达式,因此不需要{{}} 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> 

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

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