Change src img directive or filter angular

Fmrubio

I'm trying to implement a resize for images, so I don't request a big image file. Therefore, I need to change the 'src' of the img tag to redirect it to a resize service.

I have been trying to make a directive which specify the size that I want to use and $observe the ngSrc.

.directive('resizeTo', function ( imageResizeFactory ) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs) {

            var sizes = attrs.resizeTo.split('x')

            if ( !sizes.length ) {
                throw new ReferenceError('no sizes provided');
            }

            if ( el[0].nodeName !== 'IMG' ) {
                throw new ReferenceError('type of node must be IMG');
            }

            //
            // apply same width and height
            if ( sizes.length === 1 ) {
                sizes.push.apply(sizes, sizes);
            }

            var observer = attrs.$observe('ngSrc', function ( newSrc ) {
                _updateSrc( newSrc );
            });

            function _updateSrc( src ) {
                var resizeUrl = imageResizeFactory( src, sizes[0], sizes[1] )
                el.attr('src', resizeUrl);
            }
        }
    }
})

This doesn't work since there is a conflict between this directive and the angular ngSrc directive, modifying again the src attribute after it has been modified in my custom directive. I was wondering if there is a work-around to modify the 'src' after it has been interpolated by ngSrc.

I was also thinking to use a filter, instead. What do you think about it? I would like to get some feedback on this issue.

Jscti

In order to prioritize you can use the priority config param of a directive.

This way you'll be sure that your directive is being applied after ngSrc :

priority

When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related