How to get body
element in angular directive? my objective is to do what one do with jquery $('body').innerWidth();
inside directive. I do not want to use jquery but angular built-in jqlite implementation.
If you need to access the body element from within a directive that is applied on another element, you can make use of the $document service like so..
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>
You could also use the DOM traversal methods provided in jqLite (though they are much less powerful than what jQuery offers). For example, you could do a recursive lookup using the angular.element.parent()
method to find the body tag.
One more variation using the find()
implementation which is included in angular's jQLite:
app.directive("myDirective", function() {
return function(scope, element, attr) {
var body = angular.element(document).find('body');
console.log(body[0].offsetWidth);
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With