LOTUSMS LOTUSMS - 1 year ago 101
AngularJS Question

Removing items from an array with Angular

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) {
$scope.galleries = data;
}).error(function(error) {

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 class="meta">
<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>

Angular 1.5.8


Answer Source

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..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download