如何观看 img 元素的 ngSrc 并在自定义指令中获取新的宽度和高度

How can I watch ngSrc of an img element and get the new width and height inside of my custom directive?

本文关键字:获取 指令 高度 自定义 img 何观看 元素 ngSrc      更新时间:2023-09-26

index.html 片段:

<img ng-src="{{ImageURL}}"  my-image/>

应用.js:

var app = angular.module('plunker', []);
app.controller('MyCtl', function($scope) {
  $scope.ImageURL = "";
  $scope.ImgWidth = 0;
  $scope.setImgSrc = function(imgURL) {
    $scope.ImageURL = imgURL;
  };
  $scope.setImgSrc('http://angularjs.org/img/AngularJS-large.png');
});
app.directive('myImage', [function() {
  return function(scope, elm, attrs) {
    scope.$watch(elm.width(), function(newValue, oldValue) {
      scope.ImgWidth = newValue; // always returns 0!
    });
  };
}]);

这是扑通。 当ngSrc更改时,如何在自定义指令中获取 img 元素的新维度? 我有一种感觉,我没有正确调用scope.$watch.

在我看来,

你 plunk 中的手表是正确的,尽管 SO 上的例子不是,而且两者都不能做到你的期望。

监视表达式应为字符串表达式或函数。在您的示例中,您正在尝试观察elm.width()的结果...最有可能是 0。这实质上等同于说scope.$watch(0, function() {...})。如果你想观察宽度,你需要做scope.$watch(function() { return elm.width(); }, function() {...})尽管经常点击 DOM 是一个坏主意,尤其是从手表表达式中。

更好的方法是等到加载图像(使用 load 事件)并在此时更新测量值。DOM 只会在更新图像时命中。我已经在这里更新了 plunk。

它可能不值得注意,因为图像太小了,但是您在加载图像之前就获得了宽度。要解决此问题,请向元素添加加载时

app.directive('myImage', [function() {
    return function(scope, elm, attrs) {
      elm.on('load', function()
      {
        scope.ImgWidth = $(this).width();
        scope.$apply();
      });
    };
}]);

问题出在你对$watch的调用中。 $watch期望第一个参数是要评估的字符串或它可以调用然后检查其值的函数。你传递的是一个整数。试试这个:

 scope.$watch(function() { return elm.width(); }, function(newValue, oldValue) {
     scope.ImgWidth = newValue;
 });

在这里扑克:http://plnkr.co/edit/93SvAosQWkQzRq0DFXaK?p=preview

请注意,要获得 width() 函数,您还需要包含完整的 jQuery,我已经在我的 plunk 中完成了此操作。

更新 - plunk 更新以遵循@Andyrooger关于处理加载事件的建议。更好的办法是获取加载事件处理程序中的宽度,但我保持原样,以保持有关$watch问题的精神。