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:
<img ng-src="{{myFunction()}}" />
Fiddle
Right, got there in the end:
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');
}
};
});
<div ng-app="MyApp">
<div ng-controller="Ctrl2">
<img my-src />
</div>
</div>
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/