javascript - Angular - 如果 src 错误,则在指令内拼接数组

标签 javascript angularjs

如果图像不存在,我需要删除项目并在 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

为了使其更具可重用性,最好创建隔离范围并将帖子项和帖子数组传递到隔离范围

DEMO

关于javascript - Angular - 如果 src 错误,则在指令内拼接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451738/

相关文章:

javascript - 输入类型= angularjs中的数字验证

javascript - 如何在 twitter bootstrap 模式中将图像拉到左侧?

javascript - 随机使用 Boomerang.js

angularjs - 当 ngStyle 更新时更新样式属性

javascript - AngularJS 测试服务结果为 'UnknownProvider'

javascript - 尝试使用 Javascript 将字符串转换为对象,但在 ie8 中出现语法错误

javascript - 在 mobx 中使用 @computed 作为 array.length?

angularjs - 将复杂的嵌套SQL关联转换为可管理服务的前端数据建模最佳实践是什么?

angularjs - 集成测试 AngularJS + Karma + Jasmine

javascript - Angular JS Controller 未实例化