Let's start right away, Let's say this is my directive:
appDirectives.directive('myDirective', function () {
return{
restrict: 'A',
templateUrl: 'directives/template.html',
link: function (scope, element, attr) {
// maybe by element or attr access to the dom inside the template
}
};
});
And this is my template:
<div class='col-md-12 videoholder' id="sliderContainer">
<canvas id="myCanvas"></canvas>
<div class="myLangaugesholder"></div>
</div>
Normally I would use (but that's bad practice in Angular)
document.getElementById('myCanvas').style.opacity = 0.6;
my Question
How do I access the ID (for example myCanvas) inside a directive without Jquery . I tried it with the element parameter but then I only get access to the <div data-myDirective></div>
. Best Practices, Code examples are always welcome!
There are plenty native DOM methods. In your case you can just use querySelector /querySelectorAll:
appDirectives.directive('myDirective', function () {
return{
restrict: 'A',
templateUrl: 'directives/template.html',
link: function (scope, element, attr) {
var canvas = element[0].querySelector('canvas');
canvas.style.opacity = 0.6;
}
};
});
Also make sure you don't use ids inside your directive template, since directive is supposed to be reusable. This directive template is much better:
<div class='col-md-12 videoholder' class="slider-container">
<canvas class="my-canvas"></canvas>
<div class="my-langauges-holder"></div>
</div>
您可以使用:
angular.element(document.querySelector('#myCanvas'));
In directive
appDirectives.directive('myDirective', function () {
return{
restrict: 'A',
templateUrl: 'directives/template.html',
link: function (scope, element, attr) {
$(element).css('opacity', '0.6');
}
};
});
in html
<div class='col-md-12 videoholder' id="sliderContainer">
<canvas id="myCanvas" my-directive></canvas>
<div class="myLangaugesholder"></div>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.