如何在“ng-src”中调用函数

我需要能够调用一个函数,以运行代码dynamic检索图像的来源。 下面的代码片段显示了我想要的一个例子:

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

我相信这一定很简单,但在ng-src文件中找不到任何东西! 还有人打过这个?

提前致谢!

指令(基于答案的例子)

其他人推荐了一个指令 我不能发布客户端代码,所以我写了一个简短的例子,说明在plunker中可能看起来像什么( 见这里 )。 核心指令本身是:

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

我知道我在这里作为一个例子可能只是在ng-src中使用variables来完成ng-repeat,但是它可以作为一个指令的例子,如果有必要的话。

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

小提琴

对,最后到了那里:

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> 

小提琴

将myFunction作为parameter passing给自定义指令不是更好吗? 这样,我们将两者分离开来,并且可以很容易地改变将来通过哪个function。

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.orghttp://img.dovov.comroadshow-promo.png'; } }) .directive('mySrc', function() { return { restrict: 'A', scope: { callback: '&' }, link: function ( scope, elem, attrs ) { elem.attr('src', scope.callback()); } }; }) 

http://jsfiddle.net/GLS2a/