Javascript – Angularjs – get body element inside directive

angularjsjavascript

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.

Best Answer

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.