首页 > 解决方案 > 对特定指令应用 $digest

问题描述

我正在尝试使用 angular-js 制作时钟。现在我已经使用 构建了一个时钟$interval,但是在每个间隔之后,其他$directive人也得到了我想要限制的刷新。

html文件

<body ng-app="defaultDashboard">
    <div ng-controller="timeDisplay">
        <span class="glyphicon glyphicon-bell nav-link navbar-textColor" id="clock"> {{time}} </span>
    </div>
    <div ng-controller="panel">
        {{ printName('hello man!!') }}
    </div>
</body>

角文件

angular.module('defaultDashboard',[])
    .controller('timeDisplay'function($scope,$filter,$timeout,$interval){

    $scope.time = $filter('date')(new Date(), 'dd/MM/yyyy HH:mm:ss');     
    var timeRefresh = function(){
        $scope.time = $filter('date')(new Date(), 'dd/MM/yyyy HH:mm:ss');
    }
    $interval(timeRefresh,1000);
})

.controller('panel',function($scope,$timeout){
    $scope.printName = function(string){
        console.log(string);
    }
});

时钟工作正常,但在控制台中,每秒钟打印一次:

hello man!!
hello man!!
hello man!!
hello man!!.....

标签: angularjs

解决方案


这是我们使用$interval时的正常行为。

Angular 通常会重新渲染 $rootScope.$digest() 上的所有内容,由 $scope.$apply()、$interval 等调用。

但是,这个问题有一个后门可以重复渲染部分代码。在你的情况下时钟

将您的视图分成不同的范围。

例如:- 每 1000 毫秒(1 秒)更新一次的时钟可以在它自己的控制器中,使用重指令将其与范围分开。在您的情况下 printName() 函数

然后使用任何非 Angular 其他 JS 间隔(例如setInterval()而不是 $interval来更新您的时钟,并手动调用 $scope.$digest() 。

例如:-将您的 JS 文件更改为:

angular.module('defaultDashboard',[])
    .controller('timeDisplay'function($scope,$filter,$timeout,$interval){

    $scope.time = $filter('date')(new Date(), 'dd/MM/yyyy HH:mm:ss');     
    var timeRefresh = function(){
        $scope.time = $filter('date')(new Date(), 'dd/MM/yyyy HH:mm:ss');
    }

    // don't use $interval, it'll call $rootScope.$apply()
    // $interval(timeRefresh,1000);
    // Instead use setInterval with 1000ms value.
    setInterval(function () {
        timeRefresh();

        // digest only our scope, without re-rendering everything else.
        $scope.$digest();
    }, 1000);
})

.controller('panel',function($scope,$timeout){
    $scope.printName = function(string){
        console.log(string);
    }
});

推荐阅读