簡體   English   中英

Angularjs - 在body指令中獲取body元素

[英]Angularjs - get body element inside directive

如何在角度指令中獲取body元素? 我的目標是用jquery $('body').innerWidth();做什么$('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>

您還可以使用jqLit​​e中提供的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);

    };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM