Is the request $ scope. Is $ Apply () justified for this scenario?

New to AngularJS (and JavaScript frankly), but from what I have compiled, there are explicit calls in $ scope. $ apply () is needed only when changes occur outside the angular radar. The code below (pasted from this plunker ) makes me think that this will not be the case when a call is required, but this is the only way I can make it work. Is there any other approach I should take?

index.html

<html ng-app="repro">
  <head> 
    ...
  </head>
  <body class="container" ng-controller="pageController">
    <table class="table table-hover table-bordered">
        <tr class="table-header-row">
          <td class="table-header">Name</td>
        </tr>
        <tr class="site-list-row" ng-repeat="link in siteList">
          <td>{{link.name}}
            <button class="btn btn-danger btn-xs action-button" ng-click="delete($index)">
              <span class="glyphicon glyphicon-remove"></span>
            </button>
          </td>
        </tr>
    </table>
  </body>
</html>

script.js

var repro = angular.module('repro', []);

var DataStore = repro.service('DataStore', function() {
  var siteList = [];

  this.getSiteList = function(callback) {
    siteList = [ 
      { name: 'One'}, 
      { name: 'Two'}, 
      { name: 'Three'}];

    // Simulate the async delay
    setTimeout(function() { callback(siteList); }, 2000);
  }

  this.deleteSite = function(index) {
    if (siteList.length > index) {
      siteList.splice(index, 1);
    }
  };
});

repro.controller('pageController', ['$scope', 'DataStore', function($scope, DataStore) {
  DataStore.getSiteList(function(list) {

    $scope.siteList = list; // This doesn't work
    //$scope.$apply(function() { $scope.siteList = list; }); // This works

  });

  $scope.delete = function(index) {
    DataStore.deleteSite(index);
  };
}]);
+4
source share
2 answers
setTimeout(function() { callback(siteList); }, 2000);

Anglar digest. setTimeout Angular $timeout ( DataStore), $scope.$apply.

+5

setTimeout - async, angular, . , ​​, $timeout.

angular $timeout, , setTimeout, $scope.$apply()

$timeout(function() { callback(siteList); }, 2000);

$timeout , . , . , $timeout, , - , , $scope.root.$$phase, digest, .

+2

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


All Articles