我对 3 个项目进行了简单渲染,它们的特定 id 与名称字段粘合在一起。每当我删除该行时,我想仅使用要跟随的按钮来显示特定消息。当我这样做时,我在仅传递该特定行的删除 ID 时遇到问题,并且所有 n 行(此处为 3 行)都将被删除。
HTML:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<p ng-repeat="x in List" ng-show="!deleted">{{x.name}}<button ng-click="del(x.id)">Delete</button></p>
<p ng-show="deleted">This line has been deleted.</p>
</div>
<script>
//module declaration
var app = angular.module('myApp',[]);
//Controller declaration
app.controller('myCtrl',function($scope){
$scope.deleted = false;
$scope.List = [{"name":"Peter Martin","id":"1"},{"name":"Lita Schedan","id":"2"},{"name":"Jenni Markints","id":"3"}];
$scope.del = function(id){
//for this id -> only
$scope.deleted = true;
}
});
</script>
</body>
</html>
这意味着,如果我放置第 2 行的删除按钮。第一行和第二行必须带有删除按钮,但在中间行必须显示消息“此行已被删除”。
最佳答案
您基本上应该使用 Angular 过滤器显示已删除 flag
false 的行。为此,您需要确保您的 List 对象在初始加载时显示 deleted
属性为 false
。然后单击将整行对象传递给 del
方法。为了显示错误消息,您可以使用 $timeout
它将显示一条消息半秒
标记
<div>
<p ng-repeat="x in List | filter : {deleted: false}">
{{x.name}}
<button ng-click="del(x)">Delete</button>
</p>
<p ng-show="deleted">Line with id {{deletedId}} has been deleted.</p>
</div>
点击元素时将删除标志设置为true
Controller
//Controller declaration
app.controller('myCtrl',function($scope, $timeout){
$scope.deleted = false;
$scope.List = [{"name":"Peter Martin","id":"1"},{"name":"Lita Schedan","id":"2"},{"name":"Jenni Markints","id":"3"}];
angular.forEach($scope.List, function(ele){
ele.deleted = false;
})
$scope.del = function(x){ //passed object
x.deleted = true;
//for showing message
$scope.deleted = true;
$scope.deletedId = x.id;
$timeout(function(){
$scope.deleted = false;
$scope.deletedId = undefined;
}, 500)
}
});
如果您确实想从数组中删除元素,可以通过将 $index
传递给它来使用 .slice()
方法
关于javascript - AngularJs - ngRepeat 删除 View 中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35148011/