Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use $scope.$apply() frequently?

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>
like image 272
haMzox Avatar asked Nov 07 '22 22:11

haMzox


1 Answers

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.

like image 50
TheOpti Avatar answered Nov 15 '22 10:11

TheOpti