本文介绍了如何删除元素/节点从angular.js阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从阵列 $ scope.items ,以便将项目视图中的 NG-重复删除=项目中删除元素项目

I am trying to remove elements from the array $scope.items so that items are removed in the view ng-repeat="item in items"

就在这里示范的目的是有些code:

Just for demonstrative purposes here is some code:

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

我想,如果有姓名权泰德从视图中去除1个元素?它工作正常,但视图重新加载的所有元素。因为所有的数组键都转移。这是在移动应用中,我创建创建不必要的延迟。

I want to remove the 1st element from the view if there is the name ted right? It works fine, but the view reloads all the elements. Because all the array keys have shifted. This is creating unnecessary lag in the mobile app I am creating..

任何人都有一个解决这个问题呢?

Anyone have an solutions to this problem?

推荐答案

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

There is no rocket science in deleting items from array. To delete items from any array you need to use splice: $scope.items.splice(index, 1);. Here is an example:

HTML

<!DOCTYPE html>
<html data-ng-app="demo">
  <head>
    <script data-require="[email protected]" 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);
  }
}

这篇关于如何删除元素/节点从angular.js阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 02:31