当我不更改范围中的任何内容时,AngularJS 会重新评估绑定

AngularJS reevaluates bindings when I don't change anything in the scope

本文关键字:新评估 AngularJS 绑定 评估 范围 任何内      更新时间:2023-09-26

我需要在我的 Angular 应用程序中更新一个小数字"时钟"。我在控制器中使用以下代码:

        $scope.time = new Date();
        var interval = $timeout(function updateTime() {
            console.log("Update time");
            $scope.time = new Date();
            $scope.formattedTimeValue = WBUtils.formattedTime($scope.time);
            interval = $timeout(updateTime, 1000);
        }, 1000);

我使用{{formattedTimeValue}}表达式在我的 html 中的一个小div 中显示formattedTimeValue。我还有一个使用过滤器格式化数据的 ng-repeat 指令。我的问题是这些过滤器每秒都会被重新评估。我不明白为什么。我已将间隔函数更改为以下内容,但过滤器仍然会被重新评估:

            var interval = $timeout(function updateTime() {
              console.log("Update time");
              interval = $timeout(updateTime, 1000);
            }, 1000);

有人可以向我解释为什么我的过滤器每秒都会在 ng-repeat 中为每个对象(不变(进行评估。筛选器当前如下所示:

module.filter('formatLogRecord', function () {
    return function (log) {
        console.log("Filtering");
        return "";
    }
});

角度$timeout服务包括调用整个$rootScope(https://github.com/angular/angular.js/blob/v1.2.0rc1/src/ng/timeout.js#L10(的$apply,这将导致新的摘要并重新评估过滤器。如果这不是你想要的,只需使用普通的 js setTimeout 代替,并只将处理作用域的位包装在自己$scope.$apply

首先,当计时器达到 0 时,$timeout会导致 $scope.$digest((,这会重新评估绑定。其次,每次迭代时间时,您都会更改 $scope.time 和 $scope.formattedTimeValue 的值,这两者都会导致 Angular 运行摘要并重新评估您的值。