【问题标题】:How to use ng-if with asynchronous function?如何使用带有异步功能的 ng-if?
【发布时间】:2015-12-05 09:36:10
【问题描述】:

任务是在模​​板中显示图像,但前提是图像尺寸比 > 2

<img class="main-img" ng-if="showImage($index)" ng-src="{{item.img}}">

功能:

$scope.showImage = function(index) {
    var img = new Image();
    img.src = $scope.items[index].img;
    img.addEventListener("load", function() {
        var ratio = this.naturalWidth / this.naturalHeight;
        if (ratio > 2) {
            return true;
        } else {
            return false;
        }
    })
}

ng-if 不等待图像加载。怎么修?谢谢。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:
    <img class="main-img" ng-init="showImage($index)" ng-if="ImageLoad" ng-src="{{item.img}}">
    
    $scope.ImageLoad=false;
    $scope.showImage = function(index) {
        var img = new Image();
        img.src = $scope.items[index].img;
        img.addEventListener("load", function() {
            var ratio = this.naturalWidth / this.naturalHeight;
            if (ratio > 2) {
                $scope.ImageLoad=true;
                return true;
            } else {
                return false;
            }
        })
    }
    

    这样改

    【讨论】:

    • 这段代码被 ng-repeat 包裹,所以如果这个函数返回 False,则不会显示任何图像。
    • 好的,您可以尝试使用索引 $scope.ImageLoad=[]; 和函数集索引 $scope.ImageLoad[index]=true 和 img 标签集 ng-if="ImageLoad[$index] 如果您有任何问题,请告诉我。
    • 你可能需要 $timeout 在那里的某个地方。
    【解决方案2】:

    通过在函数末尾运行 $scope.$apply(),您可以强制 Angular 加载图像。

    $scope.showImage = function(index) {
      var img = new Image();
      img.src = $scope.items[index].img;
      img.addEventListener("load", function() {
          var ratio = this.naturalWidth / this.naturalHeight;
          if (ratio > 2) {
              return true;
          } else {
              return false;
          }
       })
      $scope.apply()
    }
    

    【讨论】:

    • 是的,先生,这是最直接和正确的答案,只是强制更改模型。为什么这不是公认的答案?因为大多数程序员本质上都是“贝多芬”,并且喜欢写交响乐来寻求答案:)。
    【解决方案3】:

    在上面提到的代码中,我认为应该是 'ng-init' 而不是 ng-if。如果您使用 ng-repeat 包装代码,则不会根据您提供的功能显示任何图像。你也可以设置一个超时时间。

    【讨论】:

      【解决方案4】:

      看起来这些事件发生在 Angular 的摘要周期之外。 $apply 应该可以工作,但您也可以放弃事件侦听器并绑定到返回 false 的函数,直到所需的属性在那里,但这些可能很昂贵。这种方法也可以,将加载事件/侦听图像放在指令中,然后可以调用 $scope 方法或 $broadcast 来管理 ng-if 的标志。看这个例子:Image loaded event in for ng-src in AngularJS

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 2016-11-27
        • 2016-11-29
        • 2022-06-25
        • 2017-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多