5

I was having problem when updating my list to ng-repeat in view and $scope.$apply came to the rescue. I am concerned about the watchers. Is it a good practice to use $scope.$apply() frequently? Since I am having many views in application which must be updated immediately on button click.
PS: Any alternatives are appreciated.
Sample JS code of my application:

function onRefreshList() {
    vm.showLoader = true;
    GetDataService.getVotes(someParams).then(function(res) {
    if (res){
        vm.showLoader = false;
        vm.voteList = res; //voteList will be updated on click of Refresh list 
        $scope.$apply(); //working fine with this }
    }).catch(function (res) {
        vm.showLoader = false;
        console.log("There was an error will loading votes");
    })
}

HTML:

<div ng-show="showLoader">
    <ion-spinner icon="android" class="spinner-assertive"></ion-spinner>
</div>

<div ng-show="!showLoader" ng-repeat="vote in votesCtrl.voteList">
    {{vote}}
</div>
ric
  • 627
  • 1
  • 12
  • 23
haMzox
  • 2,073
  • 1
  • 12
  • 25
  • None of the hundreds of "when to use ... ?", "best practice using ... ", "when should I use ... ?" results on your preferred search engine helped? – Andreas Apr 22 '17 at 13:25
  • Should only need to use it when code that updates scope is outside of angular context. Assuming `GetDataService.getVotes()` uses a third party javascript api you might want to look into returning `$q` promises instead. They are set up to not need `$apply()` as they call it internally – charlietfl Apr 22 '17 at 13:42
  • 2
    Possible duplicate of [When is it safe to use $scope.$apply()?](http://stackoverflow.com/questions/29817111/when-is-it-safe-to-use-scope-apply) – TheOpti Apr 22 '17 at 14:10

1 Answers1

1

AngularJS by default provides its own wrappers for JavaScript async:

  1. Directives like ng-click or ng-keydown
  2. $http service for asynchronous AJAX calls
  3. $timeout and $interval

In my opinion, it is a bad practice to use $scope.$apply() method on your own and this method shouldn't be used randomly throughout your code. If it has to, it means you did something wrong when you thought about your app/module/component.

Read more here.

Community
  • 1
  • 1
TheOpti
  • 1,641
  • 3
  • 21
  • 38