![](/img/trans.png)
[英]How can I get a reference to the enclosing form element from within an angularjs directive?
[英]How can I get and set element heights from within an AngularJS Directive
该代码的目标是:
当前的.js代码为:
app.directive('safety', function() {
return {
restrict: 'A',
link: function(scope, element) {
var section = element[0].offsetHeight;
var padding = 60;
var heading = 49;
var button = 74;
var margin = padding + heading + button;
var newHeight = section - margin;
console.log('Section: ' + section);
console.log('New height: ' + newHeight);
}
};
});
我的HTML是:
<section class="section container-fluid safety-container" safety>
<h1 class="page-header">Procedures</h1>
<div class="row">
<div class="impact-doc-link col-md-12">
<a class="btn btn-safety btn-block" href="doc/procedures.pdf" role="button">Procedures</a>
</div>
<div class="impact-pdf-container col-md-12">
<object data="doc/procedures.pdf" type="application/pdf" width="100%" height="100%">
alt : <a href="doc/procedures.pdf">doc/procedures.pdf</a>
</object>
</div>
</div>
</section>
如何从“安全”指令中将“ .impact-pdf-container”的高度设置为newHeightVariable? 我对angular js很陌生。 我是否要制定新指令? 或者我可以简单地追加指令以合并此功能。
另一件事是代替我使用变量“ padding”和“ heading”来获取指令中其他元素的高度?
您可以在指令内使用DOM方法。 由于您使用的是jQuery,因此更加简单:
app.directive('safety', function() {
return {
restrict: 'A',
link: function(scope, element) {
var section = element[0].offsetHeight;
var padding = 60;
var heading = 49;
var button = 74;
var margin = padding + heading + button;
var newHeight = section - margin;
element.find('.impact-pdf-container').height(newHeight);
}
};
});
关于如何读取元素的填充/边距。 jQuery也很容易,因此您可以使用CSS方法:
var padding = element.css('padding-left');
最佳实践表明,永远不要在控制器内部进行DOM操作。 这里有一篇文章:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.