最好的方式与Angular.js preLOAD图片 [英] Best way to preload images with Angular.js

查看:97
本文介绍了最好的方式与Angular.js preLOAD图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角的NG-SRC保持previous模型,直到它在内部preloads形象。我使用不同的图像的每个页面上的横幅,当我切换路线,我改变主视图,让头看法,因为它是只是改变bannerUrl模型时,我有。

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, leaving header view as it is, just changing bannerUrl model when I have it.

这是导致看到previous旗帜形象,而新的加载。

This is resulting in seeing previous banner image while new one is loading.

我很惊讶,没有指令来过,但我想试图建立一前作讨论。

I was surprised that there's no directive for it yet, but I wanted to make a discussion before trying to build one.

我想要做的,我认为是有自定义属性的旗帜模式。这样的:

What I want to do I think is have banner model on custom attribute. like:

<img preload-src="{{bannerUrl}}" ng-src="{{preloadedUrl}}">

然后$ scope.watch为bannerUrl变化,只要它的变化,更换NG-src和装载机微调,然后再创建一个从preLOAD-SRC,然后temproary IMG DOM元素,preLOAD图像它assing至preloadUrl。

Then $scope.watch for bannerUrl change, and as soon as it changes, replace ng-src with loader spinner first, and then create temproary img dom element, preload image from preload-src and then assing it to preloadUrl.

需要考虑如何处理多个图像太为画廊为例。

Need to think how to handle multiple images too for galleries for example.

有没有人有任何投入?或者也许有人能指点现有code?

Does anyone have any input on it? or maybe someone can point me to existing code?

我见过现有在github code使用背景图片 - 但是,这并不适合我,因为我需要动态的高度/宽度为我的应用程序响应,而我不能背景图片做

I've seen existing code on github that uses background-image - but that doesn't work for me as I need dynamic height/width as my app is responsive, and I cannot do it with background-image.

感谢您

推荐答案

有对指令的2个网址似乎触摸过于复杂。我认为是更好的是写这就像一个指令:

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

<img ng-src="{{bannerUrl}}" spinner-on-load />

和指令可以观看 NG-SRC 键,(例如)设置可见:假以微调直到图像加载。因此,像:

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
  });
}

这样的元素表现很像与 NG-SRC 属性的标准IMG,只需用螺栓上一些额外的行为。

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/

这篇关于最好的方式与Angular.js preLOAD图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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