bsr*_*bsr 18 javascript angularjs
如何body在angular指令中获取元素?我的目标是用jquery $('body').innerWidth();inside指令做什么.我不想使用jquery而是使用angular内置的jqlite实现.
jes*_*vin 33
如果您需要从应用于另一个元素的指令中访问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>
Run Code Online (Sandbox Code Playgroud)
您还可以使用jqLite中提供的DOM遍历方法(尽管它们比jQuery提供的功能强大得多).例如,您可以使用该angular.element.parent()方法进行递归查找以查找body标记.
rGi*_*Gil 10
使用find()angular的jQLite中包含的实现的另一个变体:
app.directive("myDirective", function() {
return function(scope, element, attr) {
var body = angular.element(document).find('body');
console.log(body[0].offsetWidth);
};
});
Run Code Online (Sandbox Code Playgroud)