Best way to preload images with Angular.js

前端 未结 9 905
野性不改
野性不改 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:26

    Having the 2 urls on the directive seems a touch overcomplicated. What I think is better is to write a directive that works like:

    
    

    And the directive can watch ng-src and (for example) set visibility:false with a spinner until the image has loaded. So something like:

    scope: {
      ngSrc: '='
    },
    link: function(scope, element) {
      element.on('load', function() {
        // Set visibility: true + remove spinner overlay
      });
      scope.$watch('ngSrc', function() {
        // Set visibility: false + inject temporary spinner overlay
      });
    }
    

    This way the element behaves very much like a standard img with an ng-src attribute, just with a bit of extra behaviour bolted on.

    http://jsfiddle.net/2CsfZ/47/

提交回复
热议问题