angularjs – 如何从angular.js数组中删除元素/节点

前端之家收集整理的这篇文章主要介绍了angularjs – 如何从angular.js数组中删除元素/节点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从数组中删除元素$ scope.items,以便项目在视图中删除ng-repeat =“项目中的项目”

为了演示的目的,这里是一些代码

  1. for(i=0;i<$scope.items.length;i++){
  2. if($scope.items[i].name == 'ted'){
  3. $scope.items.shift();
  4. }
  5. }

我想从视图中删除第1个元素,如果有名称ted右?它工作正常,但视图重新加载所有的元素。因为所有的数组键已经移位。这是在我创造的移动应用程序中造成不必要的滞后。

任何人都有这个问题的解决方案?

从数组中删除项目没有火箭科学。要从任何数组中删除项,您需要使用 splice:$ scope.items.splice(index,1);. Here is an example

HTML

  1. <!DOCTYPE html>
  2. <html data-ng-app="demo">
  3. <head>
  4. <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>
  5. <link rel="stylesheet" href="style.css" />
  6. <script src="script.js"></script>
  7. </head>
  8. <body>
  9. <div data-ng-controller="DemoController">
  10. <ul>
  11. <li data-ng-repeat="item in items">
  12. {{item}}
  13. <button data-ng-click="removeItem($index)">Remove</button>
  14. </li>
  15. </ul>
  16. <input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
  17. </div>
  18. </body>
  19. </html>

JavaScript

  1. "use strict";
  2.  
  3. var demo = angular.module("demo",[]);
  4.  
  5. function DemoController($scope){
  6. $scope.items = [
  7. "potatoes","tomatoes","flour","sugar","salt"
  8. ];
  9.  
  10. $scope.addItem = function(item){
  11. $scope.items.push(item);
  12. $scope.newItem = null;
  13. }
  14.  
  15. $scope.removeItem = function(index){
  16. $scope.items.splice(index,1);
  17. }
  18. }

猜你在找的Angularjs相关文章