Shikha thakur Shikha thakur - 5 months ago 7
Javascript Question

Update the data in directive when use ng-bind

I have a scenario where I have a stopwatch for every candidate.

The candidate info is in

ng-repeat
where I pass the doi (date of interview) value in
stop-watch
directive controller as below

angular.module('hrPortalApp')
.directive('stopWatch', function() {
debugger;
return {
restrict: 'A',
replace: false,
scope: {
name: "=",
time: "=",
timeOfInterview: "="
},
controller: function($scope) {
debugger;
$scope.getTimeRemaining = function(endtime) {
debugger;
$scope.t[$scope.name].total = Date.parse(endtime) - Date.parse(new Date());
$scope.t[$scope.name].seconds = Math.floor(($scope.t[$scope.name].total / 1000) % 60);
$scope.t[$scope.name].minutes = Math.floor(($scope.t[$scope.name].total / 1000 / 60) % 60);
$scope.t[$scope.name].hours = Math.floor(($scope.t[$scope.name].total / (1000 * 60 * 60)) % 24);
$scope.t[$scope.name].days = Math.floor($scope.t[$scope.name].total / (1000 * 60 * 60 * 24));
}

$scope.initializeClock = function(endtime) {
debugger;
$scope.t = {};
$scope.t[$scope.name] = {};
$scope.updateClock = function() {
debugger;
$scope.getTimeRemaining(endtime);
$scope.t[$scope.name].hours = ('0' + $scope.t[$scope.name].hours).slice(-2);
$scope.t[$scope.name].minutes = ('0' + $scope.t[$scope.name].minutes).slice(-2);
$scope.t[$scope.name].seconds = ('0' + $scope.t[$scope.name].seconds).slice(-2);

if ($scope.t[$scope.name].total <= 0) {
clearInterval($scope.timeinterval);
}
}

$scope.updateClock();
$scope.timeinterval = setInterval($scope.updateClock, 1000);
}


$scope.initializeClock($scope.timeOfInterview);
},
templateUrl: './views/stopWatchView.html'
};

});


above
$scope.t[$scope.name]
is to differentiate candidate.

The template html is as below

<div id="clockdiv">
<div class="tiles">
<span class="days" ng-bind="t[name].days"></span>
<span class="hours" ng-bind="t[name].hours"></span>
<span class="minutes" ng-bind="t[name].minutes"></span>
<span class="seconds" ng-bind="t[name].seconds"></span>
</div>
<div class="labels">
<li>Days</li>
<li>Hours</li>
<li>Mins</li>
<li>Secs</li>
</div>




I am facing problem of timer counter is not updated every time.

Any help will be appreciated.

Answer

I think your issue is because you use window.setInterval instead of $interval
So the digest cycle does not run and therefore your changes aren't noticed.

Try rewriting the line

$scope.timeinterval = setInterval($scope.updateClock, 1000);

to use angular's $interval, i.e. something like this

$scope.timeinterval= $interval($scope.updateClock, 1000)
Comments