【发布时间】:2017-05-06 11:00:12
【问题描述】:
以下指令用于从服务器连续获取数据,默认间隔为 5 秒
app.directive('livestatDataGrid', livestatDataGrid);
function livestatDataGrid($http, $interval, $window) {
return {
restrict: 'E',
templateUrl: 'directives/livestatDataGrid/livestat-datagrid.html',
scope: {
viewName: '=viewName',
gridOptions: '=',
deleteItem: '=deleteItem'
},
link: function($scope) {
var defaultSec = 5;
$scope.timerObj = {};
$scope.timerObj.selectedItem = defaultSec;
$scope.timerObj.isDisplay = true;
var timer = null;
$scope.copyVal = defaultSec;
$scope.getViewData = function(viewName) {
console.log('Came here !! Directive ', viewName);
$http.get('json/' + viewName + '.json').then(function success(response) {
$scope.metricHeader = response.data.metricHeader;
$scope.stats = response.data.stats;
}, function error(error) {
console.log("Eooor ", error)
});
};
$scope.getViewData($scope.viewName);
// Timer code
$scope.editTimer = function() {
$scope.timerObj.isDisplay = false;
};
$scope.setTimer = function() {
if ($scope.timerObj.selectedItem && isNaN($scope.timerObj.selectedItem)) {
$scope.timerObj.selectedItem = defaultSec;
}
if ($scope.copyVal != "" && $scope.copyVal == $scope.timerObj.selectedItem) {
$scope.timerObj.isDisplay = true;
return;
}
$scope.StopTimer();
$scope.copyVal = angular.copy($scope.timerObj.selectedItem);
$scope.timerObj.isDisplay = true;
$scope.startTimer();
};
// starting the timer here once directive is initialized.Using `$interval`
$scope.startTimer = function() {
console.log("in timer " + $scope.timerObj.selectedItem);
if ($scope.timerObj.selectedItem && $scope.viewName) {
//time interval for sending request to server
timer = $interval(function() {
if ($scope.viewName)
$scope.getViewData($scope.viewName);
$interval.cancel(this);
console.log(timer)
}, $scope.timerObj.selectedItem * 1000);
}
};
$scope.startTimer();
// Once the job is done, destroy the timer using `$interval.cancel`.
$scope.StopTimer = function() {
if (angular.isDefined(timer)) {
console.log("in stop timer");
$interval.cancel(timer);
}
};
//timer code ends her
}
}
}
【问题讨论】:
-
你最好提供更多细节。不清楚。
-
我正在使用控制器,并且在控制器中我给出了视图的名称,它会以 5 秒的时间间隔连续进入指令和指令调用 api。对于每个视图名称,新指令都会初始化。即视图中的 ng-repeat 视图(在控制器中我有多个选择下拉列表)对于我正在调用指令的每个视图,并且指令中的 startTimer 方法在指令初始化后启动。因此,如果我从下拉列表中的选定视图中删除任何视图。我想销毁删除视图的间隔,我应该如何确定哪个计时器将停止?
-
$scope.$on('$destroy',function(){ return $scope.stopTimer(); });为我工作。
标签: javascript angularjs angularjs-directive settimeout intervals