簡體   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