Is it good practice to use $ scope. $ Apply () often?

I had a problem updating my list to ng-repeat in the view and in $ scope. $ Apply came to the rescue. Observers are bothering me. Is it good practice to use $ scope. $ Apply () often? Since I have a lot of views in the application that need to be updated immediately when the button is clicked.
PS: Any alternatives are welcome.
Sample JS code for 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> 
+5
source share
1 answer

AngularJS provides its own wrappers for JavaScript async by default:

  • Directives like ng-click or ng-keydown
  • $http for asynchronous AJAX calls
  • $timeout and $interval

In my opinion, using the $scope.$apply() method is not recommended, and this method should not be used randomly in all code. If so, then you did something wrong when you thought about your application / module / component.

More details here .

+1
source

Source: https://habr.com/ru/post/1267050/


All Articles