Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items from an array with Angular

Tags:

angularjs

Yes, it has been asked before, and I've read all the answers but nothing seems to work. So I'm asking for an extra pair of eyes to see if you can find any singularity in my code that is making it not work as it should. (I tried this code and logic somewhere else and it seems to work fine). No errors in the console by the way

I am simply trying to remove an item from the view when someone clicks the x on the picture.

Here is the controller

app.controller('galleryController', ['$scope', '$http', function($scope, $http) {
    $http.get('data/galleries.json').success(function(data){
        $scope.galleries = data;
    }).error(function(error) {
        console.log(error);
    });

    $scope.removeGalleryItem=function(gallery){
        var removedGallery = $scope.galleries.indexOf(gallery);
        $scope.galleries.splice(removedGallery, 1);
    };
}]);

and my view

<div class="col-xs-12 col-md-3" ng-repeat="gallery in galleries" >
    <a class="gallery-item" ng-href="{{gallery.img}}" ng-class="{true:'active',false:''}[checked]"
       title="Nature Image 1" >
        <div class="image">
            <img ng-src="{{gallery.img}}" alt="Nature Image 1"/>

        </div>
        <div class="meta">
            <strong>{{gallery.title}}</strong>
            <span>{{gallery.desc}}</span>
        </div>
    </a>
    <ul class="gallery-item-controls">
        <li><label class="check"><input type="checkbox" class="icheckbox" ng-model="checked" /></label></li>
        <li><span class="gallery-item-remove"><i class="fa fa-times" ng-click="removeGalleryItem(gallery)"></i></span></li>
    </ul>
</div>

Angular 1.5.8

Thanks

like image 624
LOTUSMS Avatar asked Nov 11 '16 13:11

LOTUSMS


1 Answers

You can pass an $index in your click function like this.

<i class="fa fa-times" ng-click="removeGalleryItem(galleryItem, $event , $index)">

and use $scope.galleries.splice(index, 1); inside your click function removeGalleryItem, make sure you have index parameter too like this.

$scope.removeGalleryItem = function(gallery , event, index){
        $scope.galleries.splice(index, 1);
    };

Hope this helps..

like image 160
Punit Gajjar Avatar answered Sep 22 '22 06:09

Punit Gajjar