Angular的ng-click会在ng-repeat中更新$scope,然后使用$apply来更新dom

angular ng-click inside ng-repeat to update $scope and then use $apply to update dom

本文关键字:更新 然后 apply dom scope ng-repeat 会在 Angular ng-click      更新时间:2023-09-26

我使用的是angular 1.2

ng-repeat创建的div也包含ng-click

ng-click在点击时更新$scope

$scope的变化反映在ng-repeat中,使用$apply

It works…但是当我点击时,我得到一个错误,我认为我应用了错误的$apply

这是我的jsfiddle链接

function appcontrol ($scope, $log) {
  // declare $scope vars
  $scope.currentlist = [];
  for (var i = 0; i < 10; i++) {
    $scope.currentlist[i] = {'key':i, 'value':i};  
  }
  $scope.extra = 'My Extra';
  $scope.anotherextra = 'Another Extra';
  // click handler
  $scope.handleCellClick = function(cellnumber){
    $log.log(cellnumber + ' clicked');
    // update the $scope property
    $scope.currentlist[cellnumber].value = 'AAA';
    // push out the new change to the dom
    $scope.$apply();    
    // trigger other stuff
  }
  // click handler
  $scope.handleExtraClick = function(arg){
    $log.log('extra clicked  ', arg);
    // update the $scope property
    if (arg=='My Extra') $scope.extra = 'AAA';
    if (arg=='Another Extra') $scope.anotherextra = 'AAA';
    // push out the new change to the dom
    $scope.$apply();    
    // trigger other stuff
  }         
}
html

 <div ng-controller="appcontrol">
   <div ng-repeat="item in currentlist" id="cell{{item.value}}" ng-model="item.value" class="cell" ng-click="handleCellClick(item.key)">{{item.value}}</div>
   <div id="cell{{extra}}" ng-click="handleExtraClick(extra)">{{extra}}</div>
   <div id="cell{{anotherextra}}" ng-click="handleExtraClick(anotherextra)">{{anotherextra}}</div>
 </div>

当你使用ng-click时,Angular已经为你调用了$apply。如果你拿出所有的$scope.$apply()在你的代码,错误不会出现,它将完全相同的工作。更新小提琴

您不需要使用$scope.$apply()的方式。AngularJS自动加载$scope中的数据。$apply()用于在angular框架之外执行angular中的表达式。另外,我会很少使用这个函数,因为它会降低性能。

例如,你可以使用$apply()来处理angular之外的数据,如下所示:

//explicitly auto adjust width and height when user changes size
$scope.$apply( function(){              
    $scope.width = $window.innerWidth;
    $scope.height = $window.innerHeight;                            
}); 

点击这里查看更多信息-> https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply