Nesh Nesh - 7 months ago 8
HTML Question

Get the position of an input on click in AngularJS

I want to know the position of input box using

ng-click
. Following is the controller code in which I am consoling the event
pageX
and
clientX
but rather than giving the position for input element they are giving the values according to mouse click. Let me know if any property available to extract this info. (btw I am not looking for the directive way)

Controller Code -

myApp.controller('mainCtrl', function($scope){
$scope.clicked = function(e) {
console.clear();
console.log(e);
console.log(e.pageX);
console.log(e.clientX);
};
})


HTML Code -

<input type="text" ng-click="clicked($event)" />


Working Plnkr - http://plnkr.co/edit/f9HoVeSUwKUe9QSOB2jC?p=preview

Answer

Use Element.getBoundingClientRect() over e.target

Event.target: A reference to the object that dispatched the event.

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

var myApp = angular.module('app', []);
myApp.controller('mainCtrl', function($scope) {
  $scope.clicked = function(e) {
    console.log(e.target.getBoundingClientRect());
  };
})
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="app" ng-controller="mainCtrl">
  <input type="text" ng-click="clicked($event)" />
</div>

Comments