Angular的ng-click会在ng-repeat中更新$scope,然后使用$apply来更新dom
angular ng-click inside ng-repeat to update $scope and then use $apply to update dom
我使用的是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
相关文章:
- 获取Div Width,然后更新Scope Variable
- 更新Redux状态&然后在同一实例中获取更新状态
- Angular js,在选择元素上,我想 POST 数据以将其保存在数据库中,然后我想使用 PUT 更新它而无需重新加载
- Chrome扩展程序 - 页面更新两次,然后在YouTube上删除
- ExtJS——更改代理URL然后加载存储不会更新网格
- CSS在第一次点击jQuery.post提交时没有应用,然后在随后的点击中没有更新
- 从iframe调用Parent函数,然后更新iframe表单值
- 使用javascript将span更改为input(viceversa),然后AJAX更新输入
- 父窗口如何打开2个子窗口(“childA”和“childB”),然后让childA更新childB中的内容
- 无法更新 Javascript 对象文本中的值,然后更新页面
- 按类和自定义属性值查找元素(然后更新它)
- 复制对象,然后更新 JSON 对象中的值
- 获取 IFrame 源,然后更新输入文本框
- 创建一个带有背景图像的画布,动态更新文本,然后保存画布
- AngularJs:将一个值传递给打开ngDialog的指令,然后将更新的值反映回根作用域
- 显示空白图表,然后使用按钮更新(谷歌图表)
- 如何检查表中的新内容,然后更新浏览器选项卡标题
- 如何从javascript中POST,然后使用POST响应进行更新
- 如何从浏览器中读取和写入excel文件,然后将值更新到数据库
- 将JS数组传递给PHP,然后更新MySQL