Why directly can not call a `controller` function in` AngularJs`

advertisements

I am trying to update a clock time in a h1 element. I am trying to update the time by calling a function by setting interval, But i am not able to call. I find a solution to apply.

But i would like to understand the logic behind this. any explain me the reason why i am not able to call and why should we use the apply method..?

here is my work:

angular.module('Book', [])
.controller('MyController', function ($scope) {
    var updateClock = function() {
        $scope.clock = new Date();
    };
    setInterval(function() {
        updateClock(); //not working when i call from here...?
        //$scope.$apply(updateClock); //it works!
    }, 1000);
    updateClock(); //it works in first time.
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Book">
   <div ng-controller='MyController'>
        <input ng-model="name" type="text" placeholder="Your name">
        <h1>Hello {{ clock }}</h1>
    </div>
</div>

In short

Angular run $digest cycle on some particular event($digest cycle is actually responsible for the two way data binding or for dirty checking).The event may be when $scope function is called ,$http return data ,$timeout,$interval etc.But if you used other than this then angular does not know that any thing is change( like say setTimeout which is javascript function).So we explicitly need to tell the angular and for this angular gives us $apply.

In long

Refer this link http://tutorials.jenkov.com/angularjs/watch-digest-apply.html