Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

directive - Understanding AngularJS ng-src

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...