在指令中获取body元素

Angularjs - get body element inside directive

本文关键字:body 元素 获取 指令      更新时间:2023-09-26

如何在角指令中获得body元素?我的目标是做一个做jquery $('body').innerWidth();内部指令。我不想使用jquery,而是angular内置的jqlite实现。

如果你需要从应用于另一个元素的指令中访问body元素,你可以使用$document服务,像这样…

app.directive("myDirective", function($document) {
  return function(scope, element, attr) {
    var bodyWidth = $document[0].body.clientWidth;
    console.log("width of body is "+ bodyWidth);
  };
});
<button my-directive>Sample Button</button>

您也可以使用jqLite中提供的DOM遍历方法(尽管它们比jQuery提供的功能弱得多)。例如,您可以使用angular.element.parent()方法进行递归查找,以查找body标记。

使用find()实现的另一个变体,它包含在angular的jQLite中:

app.directive("myDirective", function() {
    return function(scope, element, attr) {
    var body = angular.element(document).find('body');
    console.log(body[0].offsetWidth);
    };
});