Получить изображение SRC в рамках директивы

0

У меня есть директива с тегом img внутри него.

angular.module('example')
     .directive('customDirective', function() {
        return {
           restrict: 'E',
           replace: true,
           transclude: true,
           scope: {}, //isolate scope
           templateUrl: 'directives/customDirective.html'
           link: function(scope, element, attrs) {
              // returns undefined
              console.log(element.find('img').src);
           }
        };
     });

шаблон директивы:

<div class="customDirective">
  <img src="image.jpg" />
</div>

Я пытаюсь получить атрибут src на теге изображения.

Теги:

2 ответа

0

var src= element.find('img'). attr ('src');

Предполагается, что существует только один тег img.

-1

Вероятно, было бы проще установить источник в вашей директиве.

директива

angular.module('example')
 .directive('customDirective', function() {
    return {
       restrict: 'E',
       replace: true,
       transclude: true,
       templateUrl: 'directives/customDirective.html'
       link: function(scope, element, attrs) {
          scope.imgSrc = 'image.jpg';
       }
    };
 });

шаблон

<div class="customDirective">
  <img ng-src="{{imgSrc}}" />
</div>

Затем ваш код управляет шаблоном, а не вам нужно читать данные из шаблона.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню