У меня есть директива с тегом 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
на теге изображения.
var src= element.find('img'). attr ('src');
Предполагается, что существует только один тег img.
Вероятно, было бы проще установить источник в вашей директиве.
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>
Затем ваш код управляет шаблоном, а не вам нужно читать данные из шаблона.