Always_a_learner
Always_a_learner

Reputation: 5055

Removing element from ng-repeat does not allow to remove or hide element from DOM

I have below code to display records using ng-repeat:

<div class="gallery">
        <div ng-cloak
             ng-repeat="photo in photos| orderBy:'-id'"
             ng-mouseLeave = "delete_btn = !delete_btn"
             ng-mouseEnter = "delete_btn = !delete_btn"
             class="gallery_block"
             id="photo_block_[[photo.id]]">
            <span title="delete photo" ng-show="delete_btn" class="delete_btn_span" rel="[[photo.id]]" id="delete_photo_[[photo.id]]">
               <img  src="{{asset('frontend/images/cross_icon.png')}}">
            </span>
            <p>
                <a href="javascript:;">
                    <img ng-click="showImagePopup([[photo.path_popup_thumbnail]]);" src={{$public_path}}./image.php?width=149&height=109&cropratio=2:1.4&image=[[photo.path_popup_thumbnail]] alt="">
                </a>
                {{--<span> </span>--}}
            </p>
        </div>

    </div>

I have to delete records for that I first have to call a function using $http and then I remove element from photos array:

  var index = $scope.photos.indexOf($('#photo_block_'+id));
        $scope.photos.splice(index, 1);

Then I remove element from DOM:

$('#photo_block_'+id).remove();

Update I have called deletePhoto function using jqyery like below:

 $(".gallery").on('click','span.delete_btn_span',function()
{   
    $scope.deletePhoto($(elem), $(elem).attr('rel'));
});

deletePhoto function further do all the work of deleting elements etc. But it does not remove element. Where as all the selectors are fine. Is removing element from photos array causing problem?

Upvotes: 0

Views: 637

Answers (1)

BAXOM
BAXOM

Reputation: 68

With angular JS, you have to deal with data. So you should put an ng-click="delete(photo)" on your span.

and create a method in your controller :

$scope.delete = function(photo) { // delete froms scope.photos here... }

to delete the photo from the list.

Your code does not work because $scope.photos.indexOf($('#photo_block_'+id)) surely return -1, because you're looking for $('#photo_block_'+id), which is a jquery object in a list of simple json object (i suppose).

So the splice method does anything, and the $scope.photos list remain unchanged, so the view is not changed, because it's build from the list by the ng-repeat directive.

ps: you should never manipulate dom element from controller, if you need to do that, you should create directive.

Upvotes: 2

Related Questions