如果图像不存在,我需要删除项目并在 ng-repeat 中推送下一个。
目前我使用下一个指令
myApp.directive("noImage", function() {
return {
link: function(scope, element, attrs) {
return element.bind("error", function() {
element.attr("src", attrs.noImage);
return element.addClass('no-img');
//return element.parent().remove();
//return element.parent().splice();
});
}
};
});
显然,如果使用 element.parent().remove()
或 splice()
它不会将下一个项目推送到数组。
这里是fiddle
另一个想法是在 Controller 中编写函数,然后从指令运行它:
$scope.splicePost = (post) =>
$scope.posts.splice( $scope.posts.indexOf(post), 1 )
问题是我不知道如何做到这一点。也许需要使用隔离范围?
最佳答案
ng-repeat
为转发器中的每个项目创建一个子范围。
这意味着在指令内您将继承父作用域数组,并可以访问每个帖子项的 scope.post
。
myApp.directive("noImage", function () {
return {
link: function (scope, element, attrs) {
element.bind("error", function () {
// get index of post in the posts array
var idx = scope.posts.indexOf(scope.post);
scope.$apply(function () {
// splice posts array
scope.posts.splice(idx, 1);
});
});
}
};
});
由于事件位于 Angular 核心之外,因此您需要告诉 Angular 在范围更改时运行摘要,这是使用 $apply
或 $timeout
为了使其更具可重用性,最好创建隔离范围并将帖子项和帖子数组传递到隔离范围
关于javascript - Angular - 如果 src 错误,则在指令内拼接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451738/