我有一个指令可以根据图像的高度和宽度重新缩放和裁剪图像。
angular.module('starter.directives', ['starter.controllers']).directive('styleImage', function () {
return {
restrict: 'A',
link: function preLink(scope, elem, attr) {
elem.on('load', function () {
styleImage(elem[0])
});
}
};
})
which styleImage 函数获取元素的宽度和高度并重新缩放和裁剪它。 我调用指令如下:
<img ng-src="{{user.image_path }}" class="user-image" style-image
id="{{'user'+user.user_id}}">
一切正常,除了当我加载页面时,指令需要花费几秒钟的时间来重新缩放和裁剪图像。所以一开始图像以它们的初始宽度和大小出现。 是否有可能在加载图像之前强制指令运行?如果可以,我该如何实现?
最佳答案
Angular 中的事件顺序是
1- Routes
检测通过浏览器请求的 URL。
2- Http 请求
获取路由中声明的 View templateUrl。
3- View
呈现在页面上。
4- 指令
View 触发
因此,先查看图像然后再查看裁剪后的图像是正常行为,
我认为解决方案是在你的指令中使用模板我的意思是这样
HTML
<style-image my-src='user.image_path'></style-image>
指令
angular.module('starter.directives', ['starter.controllers']).directive('styleImage', function () {
return {
restrict: 'E',
scope{
mySrc:"="
},
link: function preLink(scope, elem, attr) {
var img= document.createElement('img');
img.setAttribute('src',scope.mySrc)
styleImage(img)
elem.append(img);
}
};
})
关于javascript - 使用 Angular Directive(指令)在页面加载时重新缩放和裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37694809/