TechnoGeek TechnoGeek - 7 months ago 31
Javascript Question

Llive clock function in AngularJs controller

I want display Hours,Minutes ans seconds(live), I written function using

$interval
in controller but
$scope
not updating my view.

here is my view :

<div ng-controller="clockCtrl">
{{hour}}:{{min}}:{{sec}}
</div>


here is my Controller :

angular.module('myApp').controller('clockCtrl',function($scope,$interval){


$interval(callAtInterval, 1000);
});


function callAtInterval(){
console.log("this text is getting printed after each second");
var today = new Date();
h=today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
$scope.hour=h;
$scope.min=m;
$scope.sec=s;


}


The function is getting call but view is not getting updated.

Answer

Your callAtInterval function is declared outside of the controller, thus it doesn't have access to $scope. You should declare it like this:

angular.module('myApp').controller('clockCtrl',function($scope,$interval){

    function callAtInterval(){
        console.log("this text is getting printed after each second");
        var today = new Date();
        h=today.getHours();
        var m = today.getMinutes();
        var s = today.getSeconds();
        $scope.hour=h;
        $scope.minutes=m;
        $scope.sec=s;
    }

    $interval(callAtInterval, 1000);
});
Comments