How to access $scope variable in angular from chrome console

坚强是说给别人听的谎言 提交于 2019-12-02 16:33:48
Will

The scope is bound to the DOM so you need to grab an element and use some angular code to get the scope.

Your best bet is to get an element that the Controller is bound to and have a look at the scope on that.

Here is the answer How do I access the $scope variable in browser's console using AngularJS?

this is a way of getting at scope without batarang. Assuming you have references to jquery and angular on your page, you can do:

var scope = angular.element($('#selectorId')).scope();

or if you want to find your scope by controller name, do this:

var scope = angular.element($('[ng-controller=myController]')).scope();

After you make changes to your model, you'll need to apply the changes to the DOM by calling

scope.$apply();

You can either follow the asnwer of Will or install Angular Batarang Chrome extension. This will not only allow you to view and manipulate '$scope' object from, let's say your JavaScript console, but also it's a fundamental tool when developing complex AngularJS apps.

Here is one Example: I have following DOM on my angular Single Page application:

<div ng-controller="usersAppController as uac" class="ng-scope">
    <div class="tab ng-scope is-normal is-active" id="rolesTab" ref="tabs" mode="normal" target-ref="rolesContent" xng-locals="xng.userApp.roles">Roles
    </div>
</div>

and this div is present in the controller name usersAppController as uac Above here I have controller as syntax

Also note down that I am using jQuery in my application:

$($0).controller() method will give me a direct access to the uac object which is on the $scope object.

$($0).scope() will give me prototype chain for the element I have selected and if I follow that chain I will find my scope object on that element.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!