javascript - 带数组的 Angular 和 changling dom 树
问题描述
我有角度的html组件。模板是
<tr ng-repeat="item in documentList track by $index">
<td>{{item.TYPE}}</td>
<td>{{item.DATE_CREATE}}</td>
<td>
<a type="button" class="btn btn-default" ng-click="delDocument(item)">Delete</a>
</td>
</tr>
和方法 delDocument(item) 是
$scope.delDocument = function(item){
if(confirm('Do you really want to delete document?')) {
$.ajax('/ajax/del_document.php', {
'method': 'POST',
'data': {
'id': item.ID,
},
'success': function(){
i = 0;
while(i<$scope.documentList.length) {
if($scope.documentList[i].ID===item.ID) {
$scope.documentList.slice(i, 1);
}
i++;
}
}
});
}
}
所以我希望当用户按下 Delete 按钮时,ajax 会删除后端的元素,然后 documentList 会发生变化,然后 angular 会更改 dom 树。但它没有:documentList 正在改变,但 html 页面仍然是一样的。为什么会发生?我究竟做错了什么?
解决方案
执行操作后尝试$scope.$apply()
在你的成功函数内部使用。
$scope.delDocument = function(item){
if(confirm('Do you really want to delete document?')) {
$.ajax('/ajax/del_document.php', {
'method': 'POST',
'data': {
'id': item.ID,
},
'success': function(){
i = 0;
while(i<$scope.documentList.length) {
if($scope.documentList[i].ID===item.ID) {
$scope.documentList.slice(i, 1);
}
i++;
}
$scope.$apply();
// or blow is a safe way to use $scope.$apply();
// if($scope.$$phase){
// $scope.$apply();
// }
}
});
}
}
推荐阅读
- coldfusion - 如何应对这种 SQL 注入风险(Coldfusion)?
- sql-server - Docker-compose SQL Server 创建然后 attach_dbs (windows)
- itext - iText 7 在特定位置添加注释
- javascript - 我可以得到键码值吗?
- android - Android 布局管理器属性
- python - 更新类实例变量时,最好在函数内更新还是返回值并在函数调用时更新?
- javascript - 如何在 JS 中获取网页的图片
- php - Hubspot CRM API:如何过滤联系人并显示所需的属性
- python - 可执行文件显示即使在 Conda 环境中安装了软件包,也找不到模块
- r - 滚动窗口回归的 T 统计量