什么是$ scope.使用Angular处理对象/数组所需的$ apply?

Kyl*_*ell 2 soundcloud angularjs angularjs-scope

我正在使用Soundcloud JS SDK将我的Soundcloud收藏夹带入一个简单的Angular应用程序.

在我使用之前,我无法正确导入用户收藏夹$scope.$apply.

function TopListCtrl($scope, $http, $modal) {
  $scope.getData = function(sc_user) {
     SC.get('/users/'+ sc_user +'/favorites', {limit: 200}, function(tracks){
     $scope.$apply(function() {
  if (Object.getOwnPropertyNames(tracks).length > 1) {
      $scope.likes = tracks;
      $scope.sortField = 'like.favoritings_count';
      $scope.reverse = true;
      $scope.sc_user = sc_user;
     } 
  else {
      alert("That user has 0 Soundcloud likes. So sad...")
     }
  }).error(function (data, status, headers, config) {          
             alert("Something went awry with that request. Double check that's a real Soundcloud username");         

        })
        }); 
  }
Run Code Online (Sandbox Code Playgroud)

如果你不使用$ scope.apply,它就不起作用(并说SC.get未定义).

我想更好地理解为什么$scope.$apply有必要.我问这个是因为当我刚刚使用http api时,我不需要它.

function TopListCtrl($scope, $http, $modal) {
  $scope.getData = function(sc_user) {
     var url = 'http://api.soundcloud.com/users/'+ sc_user +'/favorites.json?client_id=0553ef1b721e4783feda4f4fe6611d04&limit=200&linked_partitioning=1&callback=JSON_CALLBACK';
    $http.jsonp(url).success(function(data) {
     if (Object.keys(data.collection).length > 0) {
      $scope.likes = data;
      $scope.sortField = 'like.favoritings_count';
      $scope.reverse = true;
      $scope.sc_user = sc_user;
     } 
    else {
      alert("That user has 0 Soundcloud likes. So sad...")
     }
  }).error(function (data, status, headers, config) {          
             alert("Something went awry with that request. Double check that's a real Soundcloud username");         
        });
  }
Run Code Online (Sandbox Code Playgroud)

pix*_*its 11

通常angular知道正在执行的代码,因为你是提供函数回调的那个,但它实际上是调用它们的角度.在角度调用函数之后,它将在稍后调用$ apply以触发$ digest循环.

如果您不知道$ digest循环是什么,那么这个概念很简单.在$ digest阶段,angular将对使用$ watch处理程序设置的每个范围变量进行脏检查,并检查它是否已更改; 如果它有角度将调用其相应的$ watch处理程序来更新视图.

回到最初的问题 - 当angular知道你的代码时,它会为你触发$ digest循环 - 所以没有必要明确地调用$ apply.如果你处理一个jquery事件,这是一个不同的故事.Angular不知道可能需要$ digest - 它怎么样?因此需要$ apply来手动触发$ digest.