Andrew Irwin
Andrew Irwin

Reputation: 711

Delete item from list Ionic

I'm building an ionic to do list app. I'm working on a delete function where you click the delete button and it will delete the list item, but have I'm having problems and can't figure it out. the delete button shows, but when you click it nothing happens.

HTML:

 <ion-view view-title="To-Do">
  <ion-content class="padding">



    <!-- http://ionicframework.com/docs/components/#bar-inputs -->
    <div class="bar bar-header item-input-inset">
      <label class="item-input-wrapper">
        <i class="icon  placeholder-icon"></i>
        <input type="text" ng-model="item.name" placeholder="Enter Task Here">
      </label>
      <button class="button ion-ios-plus-outline" ng-click="addItem(item)">

      </button>
    </div>

    <ion-list>
      <ion-item class="item-remove-animate" ng-repeat="item in items" >
        <h3>{{item.name}}</h3>
        <ion-option-button class="button-assertive ion-trash-a" ng-click="remove($index)"></ion-option-button>
      </ion-item>
    </ion-list>


  </ion-content>
</ion-view>

Controller:

 .controller('ShortTermCtrl', function($scope, Task) {

  $scope.data = Task.data;


  $scope.items = [];
  $scope.item = {};

  $scope.addItem = function (item) {
    $scope.items.push(item);
    $scope.item = {name: ""};

  };

  $scope.removeItem = function(index){
    $scope.items.splice(index, 1);
  };


})

Upvotes: 1

Views: 8733

Answers (3)

risuch
risuch

Reputation: 430

As per your codexample, you commented out the remove(task) function, you need to target the removeItem(index) function in your HTML

<ion-option-button class="button-assertive ion-trash-a" ng-click="removeItem(1)">

Instead of a static index number, provide the items/index itself to a generic function, then delete that array item, like so:

 $scope.removeItem = function(items, index){
  items.splice(index, 1);
 };

Your HTML will look like so:

<ion-option-button class="button-assertive ion-trash-a" ng-click="removeItem(items, $index)">

The $index is automatically exposed to your ng-repeat scope among other useful properties, you can read more in the docs of ng-repeat: https://docs.angularjs.org/api/ng/directive/ngRepeat

Upvotes: 1

alexmac
alexmac

Reputation: 19617

You use the wrong function name in view. Change it from remove to removeItem:

<ion-option-button class="button-assertive ion-trash-a" ng-click="removeItem($index)"></ion-option-button>

Upvotes: 2

Mohamed Ali
Mohamed Ali

Reputation: 4015

for ng-repeat use

ng-repeat='(index, item) in items'

to keep track of the index of every item, and pass the index to the remove function

ng-click="removeItem({{index}})"

Upvotes: 1

Related Questions