Angular Directive Element Attributes

Obtaining element attributes within a custom directive used within ng-repeat.

by Ben Foster

HTML

<div ng-app="demo" ng-controller='DemoCtrl'>
    <p ng-repeat='image in images'>
        <img ng-src='{{image}}' alt="" img-transform="" />
    </p>
</div>

JavaScript

var app = angular.module('demo', []);

app.directive('imgTransform', function () {
    return {
        retrict: 'A',
        scope: {
            src: '@ngSrc'  
        },
        link: function (scope, elem, attrs) {
            elem.attr('ng-src', 'foo');
            attrs.ngSrc = 'foo';
            elem.attr('src', 'foo');
            attrs.src = 'foo';
            scope.ngSrc = 'foo';
        }
    };
});

function DemoCtrl($scope) {   
    $scope.images = [
        'http://lorempixel.com/100/100/sports',
        'http://lorempixel.com/100/100/cats',
        'http://lorempixel.com/100/100/abstract'
    ];
}