我已经为它编写了代码,我在其中尝试将时间转换为十六进制值,然后将该十六进制值传递给背景颜色。 这是 Controller 的代码,下面是 View 的代码。感谢任何帮助。我想我在这里遗漏了一些非常小的东西,但我无法弄清楚。
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
已经需要一个 Angular 表达式,因此不需要 {{}}
。我所做的只是将表达式更改为语法正确。
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>
关于javascript - 使用 angularjs 根据时间更改背景颜色。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29313455/