使用 Angular.js 预加载图像的最佳方式 [英] Best way to preload images with Angular.js

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

问题描述

Angular 的 ng-src 会保留之前的模型,直到它在内部预加载图像.我在每个页面上为横幅使用不同的图像,当我切换路线时,我更改主视图,保留标题视图原样,只在我拥有时更改 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.

这会导致在加载新横幅图片时看到之前的横幅图片.

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 for bannerUrl 改变,一旦改变,首先将ng-src 替换为loader spinner,然后创建临时img dom 元素,从preload-src 预加载图像,然后将其分配给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.

有人对此有任何意见吗?或者有人可以指出我现有的代码?

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

我在 github 上看到了使用背景图像的现有代码 - 但这对我不起作用,因为我需要动态高度/宽度,因为我的应用程序具有响应性,而我无法使用背景图像来做到这一点.

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 个 url 似乎有点过于复杂.我认为更好的是编写一个指令,如下所示:

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 预加载图像的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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