【问题标题】:Angular directive to hide 'grandparent' of element隐藏元素“祖父母”的角度指令
【发布时间】:2015-07-13 02:38:26
【问题描述】:

我一直在使用以下代码来隐藏页面上任何“404”图像的“祖父母”,并且效果很好:

function imgError(image){
  image.parentNode.parentNode.style.display = 'none';
}

<img ng-src="{{photo.img}}" onerror="imgError(this);" id="image">

我想将此功能移动到自定义 Angular 指令中,以下是我当前的实现,但它不起作用。我认为我的问题在于错误地抓取了图像的“祖父母”元素。

指令:

angular
  .module('app')
  .directive('hideImage', hideImage);

function hideImage() {
  var directive = {
    link: link,
    restrict: 'A'
  };
  return directive;

  function link(scope, element, attrs) {
    element.bind('error', function() {
      angular.element(this).parent().parent().attr('style', attrs.hideImage);
    })
  }
}

HTML:

<div ng-repeat="photo in event.photos">
  <a ng-href="{{photo.link}}" target="_blank" title="{{photo.text}}">
    <img ng-src="{{photo.img}}" hide-image="'display: none;'" id="image">
  </a>
</div>

【问题讨论】:

  • 只是好奇:您是否尝试从 hide-image 属性中删除单引号?
  • 有机会我会试一试的。谢谢,我认为这也应该有效。

标签: javascript html css angularjs angularjs-directive


【解决方案1】:

对我来说似乎倒退了......并且在确认加载图像之前你不应该显示任何东西

<div ng-repeat="photo in event.photos" image-wrapper ng-show="imageLoaded">
  <a ng-href="{{photo.link}}">
    <img ng-src="{{photo.img}}">
  </a>
</div>

主元素上的指令现在使用ng-show,它只会在图像加载完成后显示。范围变量最初是未定义的,并使用图像的onload 事件将其设置为true

angular
  .module('app')
  .directive('imageWrapper', imageLoader);

function imageLoader() {
  var directive = {
    link: link,
    restrict: 'A'
  };
  return directive;

  function link(scope, element, attrs) {
    element.find('img')[0].onload=function(){ 
       scope.$apply(function(){ // use $apply for all events outside of angular
          scope.imageLoaded=true;
       })
    })
  }
}

另请注意,您不能在页面中重复 ID

【讨论】:

  • 如果任何图像出现错误,则所有元素都将被隐藏
  • @pankajparkar 否,因为ng-repeat 创建子作用域,该变量将仅对每个子作用域是本地的
  • 是的,但是您在ng-repeat 之外设置了imageLoaded 范围变量,并且您还没有在ng-repeat 中的任何位置创建它
  • @pankajparkar 好的..你是对的..不知道我在想什么。需要一个额外的内部元素才能将其放入子范围
  • 这就是我想说的......你的方法永远行不通。
【解决方案2】:

您应该在这里使用angular.element(this),因为您已经使用链接函数的element 参数控制元素,您应该使用jQLite .css 函数而不是使用JavaScript。

  function link(scope, element, attrs) {
    element.bind('error', function() {
      element.parent().parent().css({'display': 'none'}); //you can pass that css from attribute
    })
  }

【讨论】:

    【解决方案3】:
    hide-image="'display: none;'"
    

    应该是

    hide-image="display: none;"
    

    (没有单引号)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-14
      • 2015-07-02
      • 2019-11-09
      • 2021-03-03
      • 2018-06-18
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      相关资源
      最近更新 更多