jazzoria jazzoria - 1 month ago 9
AngularJS Question

How to delete the item from the list

Im creating an app using ionic and angularjs. In the app developing I have used swipe option from the ionic to delete the specific coupon from the main-list. The problem I problem face here is, Im only able to delete the description of the selected coupon, but not able to delete/remove the coupon from the main-list. Also I have use

$rootScope
where I have declared my
json array
. I have declare a
$scope.item
into which the selected coupon and its details are being pushed, in-order to display the description of each selected coupons. I'm going wrong somewhere in the code please help me to get it right. Thank you.

HTML:

<ion-list>
<ion-item ng-click="select_item(coupons)" ng-repeat="coupons in couponList" ng-model="coupons.selected">
{{coupons.CouponTitle}} <br>
<ion-option-button ng-click="editCoupons(coupons)">Edit</ion-option-button>
<ion-option-button class="button-assertive" ng-click="deleteSelected(coupons)">Delete</ion-option-button>
</ion-item>
</ion-list>
<hr>
<div style="text-align:center">
<div ng-repeat="item in items">
Coupon offer: {{item.data.description}}<br> Valid From: {{item.data.Fromldate}}
<br> Valid Till: {{item.data.Todate}} </div>


Controller:

$scope.items = [];
$rootScope.couponList = [{ CouponTitle: "Purchase worth $100", data: {description: "$50 off", Fromldate: "2016-09-09", Todate: "2016-09-18"}},
{CouponTitle: "Purchase worth $300", data:{description: "$75 off", Fromldate: "2016-11-09", Todate: "2016-10-19"}},
{ CouponTitle: "Purchase worth $500",data:{description: "$95 off", Fromldate: "2016-09-10", Todate: "2016-09-30"}}];

$scope.select_item = function (key) {
$scope.items.push(key);

}

$scope.deleteSelected = function () {
$scope.items.splice($scope.items.indexOf());
}

Answer

As suggested in one answer you can use the $index mechanism to remove an object from an array.

You have to delete both from items array and rootscope array

View:

<ion-option-button class="button-assertive" ng-click="deleteSelected($index,coupons)">Delete</ion-option-button>

Controller:

 $scope.deleteSelected = function (index,coupons) {
     $rootScope.couponList.splice(index,1);

     var to_delete = $scope.items.find(find_data)

     function find_data(items) { 
        return items.CouponTitle === coupons.CouponTitle;
     }

     var index = $scope.items.indexOf(to_delete);

     $scope.items.splice(index,1)


 }

HEre is a partial implemented fiddle

You should delete both the items array and also, couponList to remove in ng-repeat