How to call a function in “ng-src”

后端 未结 3 1208
借酒劲吻你
借酒劲吻你 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: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

    
        

    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/

提交回复
热议问题