How to call a function in "ng-src"

Angularjs

Angularjs Problem Overview


I need to be able to call a function in order to run code to dynamically retrieve the source of an image. The following code snippet shows an example of what I want:

<!-- "myFunction" exists in the current scope -->
<img ng-src="myFunction()" />

I'm sure this has to be simple but I just can't find anything in the ng-src documentation! Anyone else ever hit this?

Thanks in advance!

The Directive (Example based on answers)

Others recommended a directive. I can't post client code so I wrote a short example of what that would could look like in plunker (see here). The core directive itself is:

app.directive("imageSource", function (){
  return { link: function (scope, element, attrs){
      element.attr("src", scope.imageUrlArray[attrs.imageSource]);
    }
  };
});

I know that what I have here as an example could probably just be done with the ng-repeat using the variable in an ng-src but it serves as an example of what a directive would look like if one were necessary.

Angularjs Solutions


Solution 1 - Angularjs

<img ng-src="{{myFunction()}}" />

Fiddle

Solution 2 - Angularjs

Right, got there in the end:

JavaScript:

 angular.module('MyApp', [])
    .controller('Ctrl2', function($scope) {
    })
    .directive('mySrc', function() {
        return {
        restrict: 'A',
        link: function ( scope, elem, attrs ) {
             //replace test with whatever myFunction() does
             elem.attr('src', 'test1');
        }
      };
    });

HTML:

<div ng-app="MyApp">
  <div ng-controller="Ctrl2">
      <img my-src />
  </div>
</div>

Fiddle

Solution 3 - Angularjs

Wouldn't it be better to pass myFunction as an argument to the custom directive? That way, we decouple the two, and can easily change which function to pass in in the future.

HTML

<body ng-app='testApp'>
    <div ng-controller='TestCtrl'>
        <img my-src callback='myFunction()' />
    </div>
</body>

JS:

angular.module('testApp', [])
.controller('TestCtrl', function($scope) {
    $scope.myFunction = function() {
        return 'http://nodejs.org/images/roadshow-promo.png';
    }
})
.directive('mySrc', function() {
    return {
        restrict: 'A',
        scope: {
            callback: '&'
        },
        link: function ( scope, elem, attrs ) {
            elem.attr('src', scope.callback());
        }
    };
})

http://jsfiddle.net/GLS2a/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondrew_wView Question on Stackoverflow
Solution 1 - AngularjsAlwaysALearnerView Answer on Stackoverflow
Solution 2 - AngularjsLiamView Answer on Stackoverflow
Solution 3 - AngularjsDan TangView Answer on Stackoverflow