1

Directive

app.directive('mcAvatar', function() {
    return {
        restrict: 'E',
        scope: {
            width: '=width',
            src: '@src'
        },
        templateUrl: 'directives/mc-avatar/mc-avatar.html',
        link: function (scope, element, attrs) {
            console.log(element[0])
        }
    };
});

Template

<img width="{{ width }}" src="{{ src }}" alt="" class="mc-avatar-round">

Usage

<mc-avatar width="50" src="http://lorempixel.com/320/320/cats"></mc-avatar>

The element inside the link function in the directive returns :

<mc-avatar width="50" src="http://lorempixel.com/320/320/cats" class="ng-isolate-scope">
    <img width="50" src="http://lorempixel.com/320/320/cats" alt="" class="mc-avatar-round">
</mc-avatar>

which gives the the context to mg-avatar only. How do I access the img element here so that I could use bind functions?

jofftiquez
  • 7,548
  • 10
  • 67
  • 121

2 Answers2

1

Here is your required code,

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">

<mc-avatar width="50" src="http://lorempixel.com/320/320/cats"></mc-avatar>

<script>
var app = angular.module("myApp", []);
app.directive('mcAvatar', function() {
    return {
        restrict: 'E',
        replace: false,
        scope: {
            width: '=width',
            src: '@src'
        },
        
        template: '<img width="{{ width }}" src="{{ src }}" alt="" class="mc-avatar-round">',
        link: function (scope, element, attrs) {
            console.log(element.find("img"))
        }
    };
});
</script>

</body>
</html>

Please run the snippet.

Here is a working Demo

jofftiquez
  • 7,548
  • 10
  • 67
  • 121
Sravan
  • 18,467
  • 3
  • 30
  • 54
1

You can use element.find("img"); in your directive and then use the .bind statement over it to attach events.

Hope this helps!.

David R
  • 14,711
  • 7
  • 54
  • 72