如何调用"ng-src"中的函数

dre*_*w_w 47 angularjs

我需要能够调用一个函数来运行代码来动态检索图像的来源.以下代码段显示了我想要的示例:

<!-- "myFunction" exists in the current scope -->
<img ng-src="myFunction()" />
Run Code Online (Sandbox Code Playgroud)

我确定这必须简单但我在ng-src文档中找不到任何东西!还有人打过这个吗?

提前致谢!

指令(基于答案的示例)

其他人建议指示.我无法发布客户端代码,所以我写了一个简短的例子,说明在plunker中会是什么样子(见这里).核心指令本身是:

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

我知道我在这里作为一个例子可能只是使用ng-src中的变量来完成ng-repeat,但它可以作为一个指令在需要时的样子的例子.

Alw*_*ner 87

<img ng-src="{{myFunction()}}" />
Run Code Online (Sandbox Code Playgroud)

Fiddle

  • 我已经测试了这个方法并发现它不适合调用$ http服务或任何其他函数,因为,angularjs继续将该函数作为循环运行 (5认同)
  • 是的答案是正确的,但它循环太多次了.(如果在ng-重复下)这是不可取的. (2认同)

Lia*_*iam 5

对,最后到达那里:

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');
        }
      };
    });
Run Code Online (Sandbox Code Playgroud)

HTML:

<div ng-app="MyApp">
  <div ng-controller="Ctrl2">
      <img my-src />
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

小提琴