理解 AngularJS ng-src [英] Understanding AngularJS ng-src

查看:25
本文介绍了理解 AngularJS ng-src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处所述,AngularJS 指令 ng-src 用于防止浏览器在解析把手之前加载资源(例如图像).我目前正在使用以下代码:

<img ng-src="http://localhost:8081/media/{{ path }}";/>

使用以下 JavaScript:

function MyCtrl($scope, $timeout) {$超时(函数(){$scope.path = '图像/23694c70-04d7-11e3-9ba8-73fb00de24c4.png';}, 1000);};

正在从网络服务中检索路径.由于这种延迟,浏览器会尝试加载 http://localhost:8081/media/,这会导致 404.一旦检索到路径,浏览器就会发出正确的请求并加载图像.

在所有数据准备好之前阻止加载任何资源的首选方法是什么?

请参阅 jsfiddle 以举例说明我的情况.

解决方案

将整个路径放在 $scope 变量中.这样 ng-src 将等待,直到您向它提供完全解析的图像路径:

<img ng-src="{{ 路径 }}"/>

function MyCtrl($scope, $timeout) {var path = 'https://si0.twimg.com/profile_images/';$超时(函数(){$scope.path = path + '2149314222/square.png';}, 1000);};

FIDDLE

As explained here, the AngularJS directive ng-src is used to prevent the browser from loading the resource (e.g. image) before the handlebars get parsed. I'm currently using the following code:

<div ng-controller="MyCtrl">
  <img ng-src="http://localhost:8081/media/{{ path }}" />
</div>

With the following JavaScript:

function MyCtrl($scope, $timeout) {
    $timeout(function () {
        $scope.path = 'images/23694c70-04d7-11e3-9ba8-73fb00de24c4.png';
    }, 1000);
};

The path is being retrieved from a webservice. Because of this delay, the browser tries to load http://localhost:8081/media/, which causes a 404. Once the path is retrieved, the browser issues the correct request and loads the image.

What is the preferred method to prevent loading any resources until all data is ready?

Please see jsfiddle for an example illustrating my situation.

解决方案

Put the whole path inside the $scope variable. That way ng-src will wait until you provide it with the fully resolved path to the image:

<div ng-controller="MyCtrl">
  <img ng-src="{{ path }}" />
</div>

function MyCtrl($scope, $timeout) {
    var path = 'https://si0.twimg.com/profile_images/';
    $timeout(function () {
        $scope.path = path + '2149314222/square.png';
    }, 1000);
};

FIDDLE

这篇关于理解 AngularJS ng-src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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