在AngularJS上更改范围后检测图像加载

时间:2014-04-29 15:49:36

标签: angularjs directive

在角度上,我想要检测范围发生变化后何时加载图像。

我有这个:

<img ng-src="/uploads/screenshots/{{screenshot.imageURL}}" screenshotimageonload>

我知道我可以通过这样的指令检测图像加载:

angular.module('app').directive('screenshotimageonload', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          element.bind("load", function () {
            console.log("Image loaded !");
          });
        }
    }
});

并检测范围的变化,如下所示:

angular.module('app').directive('screenshotimageonload', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      scope.$watch('screenshot', function () {
        console.log("Image url change !");
      });
    }
  }
});

但是我无法弄清楚,他们两个都是如何绑定的。

1 个答案:

答案 0 :(得分:0)

所以,我找到了我想要的东西!

这个小提琴帮了我很多:http://jsfiddle.net/eyston/URrbN/

这就是我所做的:

angular.module('app').directive('screenshotimageonload', function () {
    return {
        restrict: 'A',

        // Bind the DOM events to the scope
        link: function (scope, element, attrs) {

            // Check when change scope occurs
            scope.$watch('screenshot', function () {
                if (scope.screenshot) {
                    console.log("New image url : " + scope.screenshot.imageURL);
                }
            });

            // When new image is loaded
            element.bind('load', function () {
                console.log("New image url is loaded ! " + scope.screenshot.imageURL);
            });
        }
    };
});

如果该指令可以帮助他人;)