[英]How can I watch ngSrc of an img element and get the new width and height inside of my custom directive?
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!
});
};
}]);
这是插件 。 当ngSrc
更改时, ngSrc
在我的自定义指令中获取img
元素的新维度? 我有一种感觉,我没有正确调用scope.$watch
。
在我看来,你的插件中的手表是正确的,虽然SO上的例子不是,也不能做你期望的。
监视表达式应该是字符串表达式或函数。 在你的例子中,你试图观察elm.width()
的结果......这很可能是0.这实际上相当于说scope.$watch(0, function() {...})
。 如果你想要观察宽度,你需要做scope.$watch(function() { return elm.width(); }, function() {...})
虽然打到DOM是一个坏主意经常,特别是来自表情。
更好的想法是等到图像加载(使用load
事件)并在此时更新测量结果。 只有在您的图像更新时才会点击DOM。 我在这里更新了插件。
问题在于你打电话给$ 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相关的问题的精神。
它显然是不可察觉的,因为图像太小,但是你在图像加载之前得到了宽度。 要解决此问题,请为元素添加一个on load
app.directive('myImage', [function() {
return function(scope, elm, attrs) {
elm.on('load', function()
{
scope.ImgWidth = $(this).width();
scope.$apply();
});
};
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.