Samuel K
Samuel K

Reputation: 33

Angular - push back to array after splice

I'm using next directive to splice array if image src error.

myApp.directive("noImage", function () {
    return {
        link: function (scope, element, attrs) {
            element.bind("error", function () {
                var idx = scope.posts.indexOf(scope.post);
                scope.$apply(function () {
                    scope.posts.splice(idx, 1);
                });
            });
        }
    };
});

And trying to push spliced items back with function from controller something like.

$scope.restorePosts = (function() {
      return function() {
          $scope.spliced_posts.forEach(function(x) {
          return $scope.posts.push(x);
        });
        return $scope.spliced_posts = [];
      };
    });

The question is what i should add to directive? scope.spliced_posts.push(scope.post)?

JSFIDDLE

Upvotes: 0

Views: 908

Answers (2)

charlietfl
charlietfl

Reputation: 171700

Use angular.copy() to make a copy of the original array that you receive from your api and store in your service

Upvotes: 0

JasperZelf
JasperZelf

Reputation: 2844

If I'm correct, you want to only show the images that have no "error.jpg" in them.

Removing them and later adding them to your array might not be the best solution here. You can use a filter with your ng-repeat to filter out the images with error.jpg in it.

ng-repeat="post in posts | filter:{ image_url:'!http://example.com/error.jpg'}"

If anywhere else you want to add a class to images that DO have the error in it, you can use ng-class:

ng-class="{'no-img': post.image_url=='http://example.com/error.jpg'}" ng-src="{{post.image_url}}"

http://jsfiddle.net/jkrielaars/xxL0qyy6/3/

That way your array of posts remains intact. If you want to be able to toggle between showing the posts with and without error.jpg, you could toggle the filter instead of changing your posts array.

in your controller

$scope.myFilter = null;
$scope.toggleFilter = function(){
    if( $scope.myFilter ){
        $scope.myFilter = null;
    }else{
        $scope.myFilter = { image_url:'!http://example.com/error.jpg' };
    }
}

and in the view:

<li ng-repeat="post in posts | filter:myFilter">

UPDATE

If you want to do dynamic checking to see if the image triggers an error, you can use a directive, much like the one you originally used, to add a class, or completely hide the element. I have also updated the JSfiddle. Something like this would add an error class to the parent. You could change this to whatever you like to style your parent. You could also choose to just hide the parent straight from the directive.

myApp.directive("hideNoImage", function () {
    return {
        link: function (scope, element, attrs) {
            element.bind("error", function () {
                element.parent().addClass("error");       
            });
        }
    };
});

Upvotes: 1

Related Questions