javascript - 使用 Angular Directive(指令)在页面加载时重新缩放和裁剪图像

标签 javascript jquery html css angularjs

我有一个指令可以根据图像的高度和宽度重新缩放和裁剪图像。

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/

相关文章:

javascript - 如何在嵌套数组javascript中找到最近的元素?

html - 背景显示不正确

javascript - 如何使用 jQuery 从元素中删除所有子项?

javascript - JavaScript Streams 的实际用例有哪些

javascript - 为什么是 { : y = 1 } = { b: 2 } valid and { a: 1 } = { b: 2 } a SyntaxError?

javascript - 在 jQuery 脚本中使用 em

javascript - email() 不是通过 onclick 属性实现的函数

jquery - jstree获取所有子节点

html - 引导导航栏覆盖整个页面,但不是所有页面

html - 需要一些帮助来对齐此文本