I have a question about using ng-class to change DOM class. Most of the buttons work fine, except "Two Blink" button. I have already called $scope.$digest, but the I can't see the effect on setTimeout 500ms. Why?
Any help is appreciated!
HTML Code
<html>
<title>
Angular Blink Test
</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="app.js"></script>
<body ng-app='app'>
<style>
.bk_red {background-color:red;}
.bk_blue {background-color:blue;}
</style>
<div ng-class='{bk_red: isRed, bk_blue:!isRed}' ng-controller='myController'>
<button ng-click='buttonClick0()'>Check</button>
<button ng-click='buttonClick1()'>One Blink</button>
<button ng-click='buttonClick2()'>Two Blink</button>
<button ng-click='buttonClick3()'>HTTP</button>
</div>
</body>
</html>
JavaScript Code
(function () {
'use strict';
// this function is strict...
var app = angular.module('app', []).controller('myController', function ($scope, $http) {
$scope.isRed = false;
$scope.buttonClick0 = function () {
alert('isRed=' + $scope.isRed);
};
$scope.buttonClick1 = function () {
$scope.isRed = !$scope.isRed;
console.log('buttonClick1 isRed:', $scope.isRed);
};
$scope.buttonClick2 = function () {
$scope.isRed = !$scope.isRed;
console.log('buttonClick2 isRed-1:', $scope.isRed);
setTimeout(function () {
$scope.isRed = !$scope.isRed; //change again, but NOT working!
$scope.$digest; //I guess something else should be done here.
console.log('buttonClick2 isRed-2:', $scope.isRed);
}, 500);
};
$scope.buttonClick3 = function () {
$scope.isRed = !$scope.isRed;
console.log('buttonClick3 isRed-1:', $scope.isRed);
$http(
{
method: 'GET',
url: '/data.js'
}).
then(function successCallback(response) {
$scope.isRed = !$scope.isRed;
console.log('buttonClick3 isRed-2:', $scope.isRed);
}, function errorCallback(response) {
$scope.isRed = !$scope.isRed;
console.log('buttonClick3 isRed-3:', $scope.isRed);
});
}
});
}());