Explain in detail how Angularjs customizes ng load events of Img

  • 2021-07-21 06:54:48
  • OfStack

In the process of using AngularJs, we often use some ng-events, such as ng-click, ng-change, etc. These events are defined for us by AngularJs in advance. In some cases, we will use a few dom events that are not frequently used, such as onload of img (triggered after the picture is loaded), but there is no such event in AngularJs by default, so how can we customize and add ng-load?

Simply add the following directive to the app object:


myApp.directive('imageonload', function () {
  return {
    restrict: 'A', link: function (scope, element, attrs) {
      element.bind('load', function () { 
        //call the function that was passed 
        scope.$apply(attrs.imageonload);
      });
    }
  };
})

Append events directly using the imageonload property in Html:


<img ng-src="{{src}}" imageonload="doThis()" />

Finally, write the corresponding event content in controller:


$scope.doThis=function(){
 //your own code
}

Related articles: