Jwqq
Jwqq

Reputation: 1097

How to get image source attribute inside a directive?

I have a simple image directive like this:

(function () {
    'use strict';    
    angular
        .module('myapp')
        .directive('imageTest', imageTest);
    function imageTest() {
        var directive = {
            'link': link,
            'restrict': 'A',
            'scope': {}
        };

        return directive;
    }

    function link($scope, element) {
        var src = element.src;
        console.log(src) => undefined
        // code to modify src
    }

})();

html

<img id="image" ng-src="{{myImg.url}}" image-test/>

All i need is to get image src attribute inside the directive but I can't seem to find out how to do it. Can anyone help me about it? Thanks a lot!

Upvotes: 0

Views: 277

Answers (1)

RWAM
RWAM

Reputation: 7018

In the attribute there is an expression, which will evaluate after instantiation of the directive. You can use $observe to get the value:

function link($scope, element, attrs) {
    attrs.$observe('ngSrc', function(url) {
        console.log(url);
    });
}

Upvotes: 1

Related Questions