Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - get body element inside directive

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.

like image 350
bsr Avatar asked May 23 '13 22:05

bsr


2 Answers

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.

like image 82
jessegavin Avatar answered Sep 23 '22 13:09

jessegavin


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);

    };
});
like image 34
rGil Avatar answered Sep 24 '22 13:09

rGil