Getting to Angular elements from JQuery or JavaScript to trigger validation

I currently know almost nothing about Angular, but it does look interesting enough for when I have time to look closer. I had to integrate an authentication sequence with AngularJS recently and found that it can create some barriers to a simple approach until you spend time learning about how it works. Rather than get into all that, I'm just going to share a couple tips that took me a long time to figure out because I know nothing about Angular beyond the fact that it has built-in validation for form fields. Perhaps Google brought you here due to the headline above, and these tips will help save you similar grief: How to grab Angular's scope from JavaScript, say, from the Console command line in your browser: TIP #1

//find angular scope using jquery/javascript
scope = angular.element(document.querySelector("body")).scope();

Note that "body" here could be some other scope, so you'll have to look at the source code and find the related controller, to see which element defines the current scope. More information at StackOverflow: AngularJS access controller $scope from outside. Here's the tricky one, which will make more sense when you look at the following tip also. I thought I could programmatically populate the form field for username and password, and that would be that. Instead, I discovered that Angular validation was saying "you need to enter a username" even when there clearly was a username entered. It's because the Angular model has not been updated, only the view (the webpage). To update the model, you do the following: TIP #2

// trigger angular model to become aware of javascript changes to view
angular.element($$("[name='email']")).triggerHandler('input')
angular.element($$("[name='password']")).triggerHandler('input')

Note the double $$ is because Angular wraps JQuery. And here's how I got into that situation in the first place. More information on this tip also at StackOverflow: Update Angular model after setting input value with jQuery. The other two tips have nothing to do with Angular, but are related. First, how to populate a form field from JavaScript: TIP #3

//populate form field
document.getElementsByName('email')[0].value='nobody@example.com'
document.getElementsByName('password')[0].value='*****'

By the way, another way to access that same form field:

document.querySelector('input[name="email"]')

And lastly, how to click a button on said form. TIP #4

document.querySelector('input[type="submit"]').click();

Hopefully someone finds some of this useful.

Add a comment

HTML code is displayed as text and web addresses are automatically converted.

Page top