如何body
在角度指令中获取元素?我的目标是做一个使用 jquery $('body').innerWidth();
inside 指令做的事情。我不想使用 jquery,而是使用 angular 内置 jqlite 实现。
问问题
48279 次
2 回答
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>
您还可以使用 jqLite 中提供的 DOM 遍历方法(尽管它们的功能远不如 jQuery 提供的强大)。例如,您可以使用angular.element.parent()
方法进行递归查找以查找正文标记。
于 2013-05-23T22:54:38.460 回答
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);
};
});
于 2013-05-24T01:16:03.040 回答