angularjs – 如何从angular.js数组中删除元素/节点
发布时间:2020-12-17 09:07:54 所属栏目:安全 来源:网络整理
导读:我试图从数组中删除元素$ scope.items,以便项目在视图中删除ng-repeat =“项目中的项目” 为了演示的目的,这里是一些代码: for(i=0;i$scope.items.length;i++){ if($scope.items[i].name == 'ted'){ $scope.items.shift(); }} 我想从视图中删除第1个元素
|
我试图从数组中删除元素$ scope.items,以便项目在视图中删除ng-repeat =“项目中的项目”
为了演示的目的,这里是一些代码: for(i=0;i<$scope.items.length;i++){
if($scope.items[i].name == 'ted'){
$scope.items.shift();
}
}
我想从视图中删除第1个元素,如果有名称ted右?它工作正常,但视图重新加载所有的元素。因为所有的数组键已经移位。这是在我创造的移动应用程序中造成不必要的滞后。 任何人都有这个问题的解决方案?
从数组中删除项目没有火箭科学。要从任何数组中删除项,您需要使用
splice:$ scope.items.splice(index,1);.
Here is an example:
HTML <!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="angular.js@1.1.5" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div data-ng-controller="DemoController">
<ul>
<li data-ng-repeat="item in items">
{{item}}
<button data-ng-click="removeItem($index)">Remove</button>
</li>
</ul>
<input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
</div>
</body>
</html>
JavaScript "use strict";
var demo = angular.module("demo",[]);
function DemoController($scope){
$scope.items = [
"potatoes","tomatoes","flour","sugar","salt"
];
$scope.addItem = function(item){
$scope.items.push(item);
$scope.newItem = null;
}
$scope.removeItem = function(index){
$scope.items.splice(index,1);
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
