Accessing Scope from The Console

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 5 years ago

The Chrome Dev Tools console is an amazing tool. In this lesson you'll learn how to use the console to programmatically grab scopes in your AngularJS application.

John: Using Angular, you can actually access the scope and other things from the console, so when you have a live web page, you can dive in and grab things out of the scope and modify them and whatnot.

I'm going to demonstrate this on the AngularJS homepage to show that there's no trickeration going on. I'm going to open the dev tools. I'll switch over to the elements. I'm going to select this input element here and then open my console.

$0 is a shortcut for the selected element in your elements. You can see it's the input when I type out "$0." The way to get the scope off of that element is by typing "angular element" and then wrapping the $0 and then typing "scope." That will return the scope. I'll press Up and assign a scope variable to that so that we can modify it.

On this example, you can see there is a your-name model. That's what we want to modify. If I say "scope your-name" and set that to "Bill," hit Enter, you can see that your-name is now set to "Bill." It's just that because we've done this outside of Angular, it hasn't run that whole scope/apply/digest cycle, so we have to call that manually ourselves.

I can say "scope apply" and, once I hit Enter, check the input field. Then you'll see that it automatically updated to "Bill." Just to show that again, I'll say "scope your-name = 'The Flash'," then hit Enter and say "scope apply." You'll see, hello, "The Flash."

David
David
~ 10 years ago

You can get $scope in chrome dev tools by installing Angularjs Batarang from the chrome web store. Thats pretty sweet too!

Ramiro
Ramiro
~ 10 years ago

anyone happen to know how to access the "controllers" scope when using controller as syntax? I can access the scope, but not the controller :)

John Lindquist
John Lindquistinstructor
~ 10 years ago

The "controller as" is simply on the scope, so get the scope, then scope.myController (or whatever you aliased your controller to).

Michael
Michael
~ 9 years ago

I think you can just use $scope w/o creating the var $scope = angular.element($0).scope() and it works the same.

Markdown supported.
Become a member to join the discussionEnroll Today