Understanding AngularJS ng-src

Info by example


Let's take this blogitem directive. The examples above already show you how to set a default value.


HTML :

<blogitem ng-repeat="item in items" 
          bg-src="{{ item.image }}" 
          caption="{{ item.title }}"/>

JS :

.directive( 'blogitem', function()
{
    return {
        restrict    : 'E',
        templateUrl : 'js/app/directives/blogitem.html',
        replace     : true,
        // pass these two names from attrs into the template scope
        scope       : {
            intro : '@',
            bgSrc : '@'
        }
    }
} )

HTML template :

<article>
    <img ng-src="{{ bgSrc }}"/>
    <p>{{ intro }}</p>
</article>

Hopefully it helps by your understanding of the ng-src.


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


I hit the same issue also. One thing I noticed is that if the value for ng-src is undefined then no img is fetched. Therefore, I created a utility method to concat two arguments and return a value if and only if both arguments are defined. See below.

<div ng-controller="MyCtrl">
  <img ng-src="{{MyUtil.strConcat('http://localhost:8081/media/', path)}}" />
</div>
myApp.factory('MyUtil', function() {
    return {
        strConcat: function(str1, str2) {
            return (angular.isDefined(str1) && angular.isDefined(str2)) ? 
                (str1 + str2) : undefined;
        }
    }
});

function MyCtrl($scope, $timeout, MyUtil) {
    $scope.MyUtil = MyUtil;
...
}

FIDDLE