AngularJS.ng类与$scope中的变量不同步

AngularJS. ng-class out of sync with variable in $scope

本文关键字:变量 同步 scope ng 类与 AngularJS      更新时间:2023-10-13

我有一个关于使用ng类更改DOM类的问题。除了"双闪"按钮外,大多数按钮都能正常工作。我已经调用了$scope$摘要,但我看不到对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);
                });
        }
    });
}());

http://plnkr.co/edit/z1DGyAvZMKP3zgoqSawH?p=preview

您需要调用$scope$digest(),而不是$digest。

不过,正确的做法是使用$timeout而不是setTimeout。这将正确地应用角度摘要周期内的更改。

https://docs.angularjs.org/api/ng/service/$timeout