【问题标题】:remove() on img with ng-src, border remains?使用 ng-src 在 img 上删除(),边界仍然存在?
【发布时间】:2016-08-18 11:41:36
【问题描述】:

我有一些 ng 重复的图像。

<img ng-src="{{::data.image}}" />

css:

.thumbnailImage {
  width: auto;
  max-width: 20px;
  height: auto;
  max-height: 20px;
  border: 1px solid lightslategrey;
  position: relative;
  display: block;
  margin-left: auto;
  margin-right: auto;
  background-color: white; /* in case of png */
  }


一些 {{data.image}} 为空。我想删除那些。

<img ng-src="{{::data.image}}" onerror="this.remove()" />

但是,当我这样做时,图像上的 1px 边框仍然存在?

在此之前,我有一个 ng-if 语句 (ng-src != null),但我发现这对于 Angular 观察者来说太昂贵了。

https://jsfiddle.net/8ykrkc3c/

【问题讨论】:

    标签: javascript html css angularjs


    【解决方案1】:

    试试这个

    <div ng-if="data.image">
       <img  ng-src="{{::data.image}}"  />
    </div>
    

    编辑:

    您可以为此使用客户指令。

    angular.module("app", [])
      .controller("MainCtrl", function($scope) {
        $scope.value = "https://www.google.co.in/images/srpr/logo11w.png";
      //  $scope.value = "null";
      })
      .directive('custSrc', function() {
        return {
          restrict: "A",
          scope: {
            value: "=custSrc"
          },
          link: function(scope, element, attrs) {
              if(scope.value == 'null')
                 element.parent().addClass('hide'); 
              else
                element.attr('src', scope.value);
            
            console.log(element);
    
          }
        };
      });
    .hide{
      display:none;
      }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
     <div ng-app="app" ng-controller="MainCtrl">
       <img  cust-src="value" />
     </div>

    【讨论】:

    • 所以为此使用custome指令。
    • @AndersPedersen 你也可以绑定一次,如果src不会改变
    【解决方案2】:

    您的 onerror 处理程序不正确。请注意,它不再是 Angular 属性,因此您不能使用 angular.element.prototype.remove 方法。相反,您需要使用良好的旧原生 DOM 方法,在您的情况下 removeChild:

    <img class="asd" ng-src="{{::data.image}}" onerror="this.parentNode.removeChild(this)" />
    

    演示: https://jsfiddle.net/8ykrkc3c/2/

    【讨论】:

    • 您的演示使用ng-src 而不是src。因为您的演示中没有 Angular ng-src 并不意味着和做任何事情,因此没有 src 属性。如果没有 src,则不会为 img 元素触发 onload/onerror 事件。
    猜你喜欢
    • 2021-03-08
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多