AngularJS - 图像“加载"事件 [英] AngularJS - Image "onload" event

查看:33
本文介绍了AngularJS - 图像“加载"事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找简单但并非微不足道的问题的答案:仅使用 jqLit​​e 在 Angular 中捕获图像'onload 事件的正确方法是什么?我发现了 这个问题,但我想要一些解决方案带有指令.
所以正如我所说,这对我来说是不可接受的:

.controller("MyCtrl", function($scope){//...img.onload = 函数 () {//...}

因为它在控制器中,而不是在指令中.

解决方案

这里有一个可重用的指令,与 angular 的内置事件处理指令的风格相同:

angular.module('sbLoad', []).directive('sbLoad', ['$parse', function ($parse) {返回 {限制:'A',链接:函数(范围,元素,属性){var fn = $parse(attrs.sbLoad);elem.on('load', 函数(事件){范围.$应用(函数(){fn(scope, { $event: event });});});}};}]);

当 img 加载事件被触发时,sb-load 属性中的表达式与加载事件一起在当前范围内计算,作为 $event 传入.使用方法如下:

HTML

<img sb-load="onImgLoad($event)">

JS

 .controller("MyCtrl", function($scope){//...$scope.onImgLoad = 函数(事件){//...}

注意:sb"只是我用于自定义指令的前缀.

I've been searching for an answer to simple but not trivial question: What is a right way to catch image' onload event in Angular only with jqLite? I found this question , but I want some solution with directives.
So as I said, this is not accepted for me:

.controller("MyCtrl", function($scope){
    // ...
    img.onload = function () {
        // ...
    }

because it is in controller, not in directive.

解决方案

Here's a re-usable directive in the style of angular's inbuilt event handling directives:

angular.module('sbLoad', [])

  .directive('sbLoad', ['$parse', function ($parse) {
    return {
      restrict: 'A',
      link: function (scope, elem, attrs) {
        var fn = $parse(attrs.sbLoad);
        elem.on('load', function (event) {
          scope.$apply(function() {
            fn(scope, { $event: event });
          });
        });
      }
    };
  }]);

When the img load event is fired the expression in the sb-load attribute is evaluated in the current scope along with the load event, passed in as $event. Here's how to use it:

HTML

<div ng-controller="MyCtrl">
  <img sb-load="onImgLoad($event)">
</div>

JS

  .controller("MyCtrl", function($scope){
    // ...
    $scope.onImgLoad = function (event) {
        // ...
    }

Note: "sb" is just the prefix I use for my custom directives.

这篇关于AngularJS - 图像“加载"事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆