angularjs - 对特定指令应用 $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!!.....
解决方案
这是我们使用$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);
}
});
推荐阅读
- youtube-api - Webhooks/PubSubHubbub 用于其他事件,例如超级聊天消息?
- ios - 在 Gmail iOS 应用程序中单击链接时强制打开默认浏览器
- read-the-docs - 网格表不自动换行
- python - 如何使用 python requests.get “跳过”第一个响应
- webpack - 将 webpack 4 更新为 webpack 5 获取错误选项具有未知属性“内联”
- flutter - 如何在颤动的sqlite中保存颜色
- java - 使用应用程序上下文在android api 17中膨胀视图时,无法在android自定义toast的布局中使用材质主题属性
- python - 如何克服 PySimpleGUI 中的“NoneTypeObject”错误?
- java - 如何从 char 数组生成组合?
- r - R shiny 中的下载处理程序不会生成 PDF 文件(使用 rmarkdown::render())