Best way to preload images with Angular.js

前端 未结 9 896
野性不改
野性不改 2020-12-07 16:04

Angular\'s ng-src keeps previous model until it preloads image internally. I am using different image for the banner on each page, when I switch routes, i change main view,

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 16:32

    If anyone is interested this is my final solution: I use twitter bootstrap. So added class of "fade" to all images and just toggling class "in" with directive to fade in and out when image is loaded

    angular.module('myApp').directive('imgPreload', ['$rootScope', function($rootScope) {
        return {
          restrict: 'A',
          scope: {
            ngSrc: '@'
          },
          link: function(scope, element, attrs) {
            element.on('load', function() {
              element.addClass('in');
            }).on('error', function() {
              //
            });
    
            scope.$watch('ngSrc', function(newVal) {
              element.removeClass('in');
            });
          }
        };
    }]);
    
    
    

    Working example: http://ishq.org

提交回复
热议问题