jgerstle
jgerstle

Reputation: 1684

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.

Upvotes: 0

Views: 1907

Answers (3)

davidmdem
davidmdem

Reputation: 3823

With document.activeElement, you can access the list of attributes on the returned element like this:

var nameOfModel = document.activeElement.attributes['ng-model'].value;

Upvotes: 0

Paritosh
Paritosh

Reputation: 11570

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'
alert(ele.attr('ng-model'));

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.

Upvotes: 1

kaushik dey
kaushik dey

Reputation: 102

input/element In Angularjs will bind a ng-model.Without using id or classes to get the element DOM can use $('[ng-model="Model"]') But If the model is under ng-repeat.

if you write and to get the element use $('[ng-model="name"]'), it will inject that particular element from the DOM.

Upvotes: 0

Related Questions