Anusha Bayya
Anusha Bayya

Reputation: 103

Remove last element from list in angularjs

  <div class="col-md-2">
    <md-button class="md-raised md-primary" ng-click="deleteDiv()">Remove</md-button>
  </div>
scope.deleteDiv = function() {
        alert(scope.itemsToAdd.length);
        if(scope.itemsToAdd.length > 1) {
            scope.itemsToAdd.splice(scope.itemsToAdd.length,1)
        }
    };

Hi.I am new to AngularJs.I have a doubt on removing a dynamically created div. itemsToAdd is an array which contains four fields.I add those fields dynamically using push and ng-repeat.When Remove button is clicked I get the length of the array and only delete if it is greater than 1. The removing procedure I posted,Is is correct? where am i doing wrong?.Thanks

Upvotes: 0

Views: 2231

Answers (3)

Avantika Saini
Avantika Saini

Reputation: 792

You need to pass the index of the element to be deleted as the parameter of the splice function:

if(scope.itemsToAdd.length > 1) {
     scope.itemsToAdd.splice(scope.itemsToAdd.length-1,1); //index of the last element is the length of the array minus 1
}

Upvotes: 2

Utku Apaydin
Utku Apaydin

Reputation: 162

<tr ng-repeat="person in persons track by $index">
        <td>{{person.name}} - # {{person.id}}</td>
        <td>{{person.description}}</td>
        <td nowrap=nowrap>
            <a href="#!/edit"><i class="icon-edit"></i></a>
            <button ng-click="delete($index)"><i class="icon-minus-sign"></i></button>
        </td>
</tr>

and in the controlelr

$scope.delete=function(index){
    $scope.persons.splice(index,1);
}

Upvotes: 0

Mohammed
Mohammed

Reputation: 658

GO through this, Its one of the type you want

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">

<h2>My Todo List</h2>

<form ng-submit="todoAdd()">
    <input type="text" ng-model="todoInput" size="50" placeholder="Add New">
    <input type="submit" value="Add New">
</form>

<br>

<div ng-repeat="x in todoList">
    <input type="checkbox" ng-model="x.done"> <span ng-bind="x.todoText"></span>
</div>

<p><button ng-click="remove()">Remove marked</button></p>

<script>
var app = angular.module('myApp', []); 
app.controller('todoCtrl', function($scope) {
    $scope.todoList = [{todoText:'Clean House', done:false}];

    $scope.todoAdd = function() {
        $scope.todoList.push({todoText:$scope.todoInput, done:false});
        $scope.todoInput = "";
    };

    $scope.remove = function() {
        var oldList = $scope.todoList;
        $scope.todoList = [];
        angular.forEach(oldList, function(x) {
            if (!x.done) $scope.todoList.push(x);
        });
    };
});
</script>

Upvotes: 0

Related Questions