我试图从数组中删除元素$ 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);
- }
- }