javascript - Why directly not able to call a function from `controller` in `AngularJs` -
i trying update clock time in h1
element. trying update time calling function setting interval, not able call. find solution apply
.
but understand logic behind this. explain me reason why not able call , why should use apply method..?
here work:
angular.module('book', []) .controller('mycontroller', function ($scope) { var updateclock = function() { $scope.clock = new date(); }; setinterval(function() { updateclock(); //not working when call 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 particular event($digest cycle responsible 2 way data binding or dirty checking).the event may when $scope function called ,$http return data ,$timeout,$interval etc.but if used other angular not know thing change( settimeout javascript function).so explicitly need tell angular , angular gives $apply.
in long
refer link http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
Comments
Post a Comment