javascript - Why is $timeout is needed for watch to trigger -
i have directive watches height of element. element updated controller uses factory method data. unless have $timeout
in factory watch never gets updated. curious! can shed light onto why?
my controller:
$scope.update = function () { apiservice.getlinks(function (response) { $scope.links = response; // if try $scope.$apply() here says in progress, you'd expect }); } quicklinksservices.factory('quicklinksapiservice', function ($http, $timeout) { quicklinksapi.getquicklinks = function (success) { //without watch in directive doesnt triggered $timeout(function () { }, 100); $http({ method: 'json', url: '/devices/getquicklinkcounts' }).success(function (response) { quicklinksapi.quicklinks = response; quicklinksapi.savequicklinks(); success(response); }); }
the directive i'm using here
basically angularjs provides $timeout service trigger function call after specified time, know use of $timeout not strictly needed, people have habit of writing mean need trigger watch after specified interval. in many cases $apply trick. thing need $apply(). reference please check this
also many times happens angulars $watch executes faster expected may send incomplete updates or response in such cases $timeout plays important role delaying $watch. can clear $timeout if $watch fast enough need, means $timeout way explicitly trigger $watch, $apply can itself. use of $timeout or $apply depends on how requirement is. hope clears you. luck.
Comments
Post a Comment