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

时间:2013-10-14 22:28:10

标签: javascript angularjs

index.html代码段

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

app.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!

    });

  };

}]);

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

3 个答案:

答案 0 :(得分:2)

在我看来,你的插件中的手表是正确的,虽然SO上的例子不是,但也不能做你期望的。

监视表达式应该是字符串表达式或函数。在您的示例中,您试图查看elm.width()的结果...这很可能是0.这基本上等同于说scope.$watch(0, function() {...})。如果你想观察你需要做scope.$watch(function() { return elm.width(); }, function() {...})的宽度,虽然经常点击DOM是一个坏主意,特别是从监视表达式。

更好的想法是等到图像加载(使用load事件)并在此时更新测量结果。只有在您的图像更新时才会点击DOM。我已更新了插件here

答案 1 :(得分:0)

问题在于你打电话给$ 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有关的问题的精神。

答案 2 :(得分:0)

这显然是不可察觉的,因为图像太小,但是你在图像加载之前得到了宽度。要解决这个问题,可以在元素上添加一个载荷

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