This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Accessing Scope from The Console

1:40 Angular 1.x lesson by

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.


egghead.io comment guidelines

Avatar
egghead.io

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.

Avatar
Reuben

I have always wanted to know how to do this. Thanks!

In reply to egghead.io
Avatar
Darijo

Chrome has extension for Angular, so you can observe scopes and relations between them more easily.

In reply to Reuben
Avatar
David

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

Avatar
Ramiro

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

Avatar
John

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

In reply to Ramiro
Avatar
Michael

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

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."

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?