Development Tip

angular.js 배열에서 요소 / 노드를 제거하는 방법

yourdevel 2020. 11. 2. 19:50
반응형

angular.js 배열에서 요소 / 노드를 제거하는 방법


$scope.items뷰에서 항목이 제거되도록 배열에서 요소를 제거하려고합니다.ng-repeat="item in items"

여기에 몇 가지 코드가 있습니다.

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

ted라는 이름이 있으면 뷰에서 첫 번째 요소를 제거하고 싶습니다. 잘 작동하지만 뷰는 모든 요소를 ​​다시로드합니다. 모든 배열 키가 이동했기 때문입니다. 이로 인해 제가 만들고있는 모바일 앱에서 불필요한 지연이 발생합니다 ..

누구든지이 문제에 대한 해결책이 있습니까?


배열에서 항목을 삭제하는 데는 로켓 과학이 없습니다. 어떤 배열에서 삭제 항목에 당신은 사용할 필요가 splice: $scope.items.splice(index, 1);. 다음은 예입니다 .

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>

자바 스크립트

"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 Way"는 $ filter를 사용하는 것입니다. $ filter를 컨트롤러에 삽입하고 다음을 수행하십시오.

$scope.items = $filter('filter')($scope.items, {name: '!ted'})

추가 라이브러리를로드하거나 자바 스크립트 프리미티브에 의존 할 필요가 없습니다.


일반 자바 스크립트를 사용할 수 있습니다 -Array.prototype.filter ()

$scope.items = $scope.items.filter(function(item) {
    return item.name !== 'ted';
});

shift()배열에서 수행 하면 배열의 길이가 변경되기 때문입니다. 따라서 for 루프가 엉망이 될 것입니다. 이 문제를 피하기 위해 끝에서 앞으로 반복 할 수 있습니다 .

Btw, 배열의 첫 번째 요소가 아닌 i 위치에서 요소를 제거하려고한다고 가정합니다 . ( $scope.items.shift();코드에서 배열의 첫 번째 요소를 제거합니다)

for(var i = $scope.items.length - 1; i >= 0; i--){
    if($scope.items[i].name == 'ted'){
        $scope.items.splice(i,1);
    }
}

여기 filterUnderscore library당신이, 우리가 "테드"이름을 가진 항목을 제거 할 수 도움말

$scope.items = _.filter($scope.items, function(item) {
    return !(item.name == 'ted');
 });

'각도'솔루션에 대한 약간의 확장입니다. 숫자 ID를 기반으로 항목을 제외하고 싶었으므로! 접근 방식이 작동하지 않습니다. {name : 'ted'} 또는 {id : 42}에 대해 작동하는보다 일반적인 솔루션은 다음과 같습니다.

mycollection = $filter('filter')(myCollection, { id: theId }, function (obj, test) { 
                                                             return obj !== test; });

@madhead에서 제공하는 솔루션이 마음에 들었습니다.

그러나 내가 가진 문제는 정렬 된 목록에서 작동하지 않으므로 인덱스를 삭제 기능에 전달하는 대신 항목을 전달 한 다음 indexof를 통해 인덱스를 얻었습니다.

예 :

var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);

업데이트 된 버전의 madheads 예제는 다음과 같습니다. link to 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|orderBy:'toString()'">
          {{item}}
          <button data-ng-click="removeItem(item)">Remove</button>
        </li>
      </ul>
      <input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
    </div>
  </body>
</html>

자바 스크립트

"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(item){
    var index = $scope.items.indexOf(item);
    $scope.items.splice(index, 1);
  }
}

이에 대한 내 솔루션 (성능 문제를 일으키지 않음) :

  1. remove 메서드를 사용하여 배열 개체를 확장합니다 (단 한 번 이상 필요함).
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

I'm using it in all of my projects and credits go to John Resig John Resig's Site

  1. Using forEach and a basic check:
$scope.items.forEach(function(element, index, array){
          if(element.name === 'ted'){
              $scope.items.remove(index);
          }
        });

At the end the $digest will be fired in angularjs and my UI is updated immediately without any recognizable lag.


If you have any function associated to list ,when you make the splice function, the association is deleted too. My solution:

$scope.remove = function() {
    var oldList = $scope.items;
    $scope.items = [];

    angular.forEach(oldList, function(x) {
        if (! x.done) $scope.items.push( { [ DATA OF EACH ITEM USING oldList(x) ] });
    });
};

The list param is named items. The param x.done indicate if the item will be deleted. Hope help you. Greetings.


Using the indexOf function was not cutting it on my collection of REST resources.

I had to create a function that retrieves the array index of a resource sitting in a collection of resources:

factory.getResourceIndex = function(resources, resource) {
  var index = -1;
  for (var i = 0; i < resources.length; i++) {
    if (resources[i].id == resource.id) {
      index = i;
    }
  }
  return index;
}

$scope.unassignedTeams.splice(CommonService.getResourceIndex($scope.unassignedTeams, data), 1);

My solution was quite straight forward

app.controller('TaskController', function($scope) {
 $scope.items = tasks;

    $scope.addTask = function(task) {
        task.created = Date.now();
        $scope.items.push(task);
        console.log($scope.items);
    };

    $scope.removeItem = function(item) {
        // item is the index value which is obtained using $index in ng-repeat
        $scope.items.splice(item, 1);
    }
});

My items have unique id's. I am deleting one by filtering the model with angulars $filter service:

var myModel = [{id:12345, ...},{},{},...,{}];
...
// working within the item
function doSthWithItem(item){
... 
  myModel = $filter('filter')(myModel, function(value, index) 
    {return value.id !== item.id;}
  );
}

As id you could also use the $$hashKey property of your model items: $$hashKey:"object:91"

참고URL : https://stackoverflow.com/questions/18303040/how-to-remove-elements-nodes-from-angular-js-array

반응형