jgerstle jgerstle - 1 year ago 63
AngularJS Question

Is there a way to get the name of an ng-model from an element

I want to find the name of the model on the active element. Basically I have document.activeElement how do I find out what it's ng-model is.

<input ng-model="myModel">

So in the above control if that was active how would I be able to find out that we are in the element with the ng-model of myModel. This is technically a workaround for adding an id or a name, but I would rather not do it if I can

As an aside this code is in the controller not a directive.

Answer Source

Here is the Fiddle
You need to get the element object as discribed in the comment in the code and then access it with attr

// get element
var result = document.getElementsByTagName("input")[0];

// get object using jQLite or jQuery
var ele = angular.element(result);

// access 'ng-model' as 'attribute'

CAUTION: Here it's shown just for example considering just one input element. Use proper class/element/attribute selector to get proper element you want to target.