Understanding AngularJS ng-src

Martijn picture Martijn · Aug 14, 2013 · Viewed 61.2k times · Source

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 JS:

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.

Thanks,

Martijn

Answer

Stewie picture Stewie · Aug 14, 2013

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