How to call a function in “ng-src”

后端 未结 3 1179
借酒劲吻你
借酒劲吻你 2020-12-24 00:59

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:

相关标签:
3条回答
  • 2020-12-24 01:14
    <img ng-src="{{myFunction()}}" />
    

    Fiddle

    0 讨论(0)
  • 2020-12-24 01:16

    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

    0 讨论(0)
  • 2020-12-24 01:19

    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/

    0 讨论(0)
提交回复
热议问题