Javascript 不带Jquery的AngularJs DOM操作内部指令
让我们马上开始,假设这是我的指令:Javascript 不带Jquery的AngularJs DOM操作内部指令,javascript,jquery,html,css,angularjs,Javascript,Jquery,Html,Css,Angularjs,让我们马上开始,假设这是我的指令: appDirectives.directive('myDirective', function () { return{ restrict: 'A', templateUrl: 'directives/template.html', link: function (scope, element, attr) { // maybe by element or attr acces
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
}
};
});
这是我的模板:
<div class='col-md-12 videoholder' id="sliderContainer">
<canvas id="myCanvas"></canvas>
<div class="myLangaugesholder"></div>
</div>
我的问题
如何在没有Jquery的情况下访问指令中的ID(例如myCanvas)。我用element参数尝试了它,但是我只能访问
欢迎您选择最佳实践和代码示例 In指令
appDirectives.directive('myDirective', function () {
return{
restrict: 'A',
templateUrl: 'directives/template.html',
link: function (scope, element, attr) {
$(element).css('opacity', '0.6');
}
};
});
在html中
<div class='col-md-12 videoholder' id="sliderContainer">
<canvas id="myCanvas" my-directive></canvas>
<div class="myLangaugesholder"></div>
</div>
有很多本机DOM方法。在您的情况下,只需使用/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;
}
};
});
还要确保不要在指令模板中使用ID,因为指令应该是可重用的。此指令模板更好:
<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'));
使用``查看提供的内容。我会这样做:
element.find('canvas')
。除非在指令中设置值,否则不要在模板中使用id。否则,您将该指令限制为只能在页面上使用一次。@JqueryKingtemplateUrl:“directives/template.html”
OP在没有jQuery的情况下说。
angular.element(document.querySelector('#myCanvas'));