我有一个关于使用ng-class来改变DOM类的问题。 大多数按钮工作正常,除了"两个闪烁"按钮。 我已经调用了$ scope。$ digest,但是我无法看到对setTimeout 500ms的影响。为什么呢?
感谢任何帮助!
HTML代码
<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代码
(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);
});
}
});
}());
答案 0 :(得分:1)
如果你想开始一个摘要周期,你需要调用$ scope。$ digest()而不是$ digest。
但是,正确的做法是使用$ timeout而不是setTimeout。这将在角度摘要周期内正确应用更改。