To access ng-model elements using DOM methods [document.getElementById etc]

706 views
Skip to first unread message

Pat

unread,
Mar 21, 2016, 6:41:03 PM3/21/16
to AngularJS
I have defined the following element in angular JS

<input type="text" ng-model="username">

I can access it using $scope.username in controller etc. So far so good. 

How can I access it from using DOM model?

var elem = document.getElementById('username');   //does not work
elem.value = "Some value";
console.dir(elem);

var elem = document.getElementById('ng-model="username"'); //does not work
elem.value = "Some value";
console.dir(elem);

This may not be the recommended, but wish to know.

Thanks!

Sander Elias

unread,
Mar 22, 2016, 12:34:58 AM3/22/16
to AngularJS
Hi Pat,

You can read from an input element that has an ng-model (well after it is processed), but setting it will lead to issues. You better do that in your controllers/components.

var elem=document.querySelector('[ng-model="username"]')
console
.log(elem.value)


Regards
Sander

Pat

unread,
Mar 22, 2016, 10:48:43 AM3/22/16
to AngularJS
Hi Sander,

Thank you so much!

Pat
Reply all
Reply to author
Forward
0 new messages