I have a div in my view, I want to execute a function on ng-click() which turns the background for the div to \'color a\' for 30 seconds if there\'s no action t
I would approach it by using a variable in the scope to hold the state, and chaining $timeout
s to move between the states. So on the element that will be clicked:
Click me to start
and in the controller:
$scope.state = 'a';
$scope.startChange = function() {
$scope.state = 'b';
return $timeout(angular.noop, 30 * 1000).then(function() {
$scope.state = 'c';
return $timeout(angular.noop, 60 * 1000);
}).then(function() {
$scope.state = 'd';
return $timeout(angular.noop, 120 * 1000);
}).then(function() {
$scope.state = 'e'
});
}
The angular.noop
is just a function that does nothing. It's a slightly personal preference, but I find it a bit easier to see the flow of activity where the callback passed to $timeout
does nothing, and all action on the scope are always in the then
success callback of the promise.
In the template for the background div:
....
and then in CSS set the colours:
.background-state-a {background-color: red}
.background-state-b {background-color: green}
.background-state-c {background-color: blue}
...
However, I'm not sure what else you have in the controller or your exact use-case. You might want to separate some logic out into a directive, as it might be mixing business logic with view logic.