Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs get element position

In jQuery we can get position of an object with this:

$(this).position().left;

How can we get the current element position with AngularJS?

like image 872
user1995781 Avatar asked Dec 20 '14 14:12

user1995781


People also ask

What is jqLite?

jqLite is a tiny, API-compatible subset of jQuery that allows AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most commonly needed functionality with the goal of having a very small footprint. To use jQuery , simply ensure it is loaded before the angular. js file.

What is ng repeat?

Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What is angular element in AngularJS?

The angular. element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular. element can be either used as an alias for the jQuery function or it can be used as a function to wrap the element or string in Angular's jqlite.


1 Answers

You can use prop() from angular jqlite. to select an element you can use querySelector() that returns first matching element or querySelectorAll() that return all matching element

angular.element(document.querySelector('yourelement')).prop('offsetLeft');

or if your "this" is valid dom element

angular.element(this).prop('offsetLeft');

Example for div

you can reference the DOM object with $event in html and pass it to the function on controller

<div ng-click="myfunction($event)"></div>

in controller

$scope.myfunction = function($event){
 console.log(angular.element($event.target).prop('offsetLeft'));

}

Demo

app = angular.module('test',[]);
app.controller('testctrl',function($scope){

  
  $scope.myfunction = function($event){
    console.log($event);
 off =angular.element($event.target).prop('offsetLeft');
  angular.element($event.target).text(off)

}
  
});
.divvy{position:absolute; left:60px;
width:100px; background:red;
}
   

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div  ng-controller="testctrl" ng-app="test">
   <div class="divvy" ng-click="myfunction($event)" >Click to see position</div>
  </div>
like image 163
A.B Avatar answered Sep 17 '22 13:09

A.B