I would like to access my $scope
variable in Chrome\'s JavaScript console. How do I do that?
I can neither see $scope
nor the name of my mo
One caveat to many of these answers: if you alias your controller your scope objects will be in an object within the returned object from scope()
.
For example, if your controller directive is created like so:
<div ng-controller="FormController as frm">
then to access a startDate
property of your controller, you would call angular.element($0).scope().frm.startDate
To improve on jm's answer...
// Access whole scope
angular.element(myDomElement).scope();
// Access and change variable in scope
angular.element(myDomElement).scope().myVar = 5;
angular.element(myDomElement).scope().myArray.push(newItem);
// Update page to reflect changed variables
angular.element(myDomElement).scope().$apply();
Or if you're using jQuery, this does the same thing...
$('#elementId').scope();
$('#elementId').scope().$apply();
Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0
.
angular.element($0).scope();
If you have installed Batarang
Then you can just write:
$scope
when you have the element selected in the elements view in chrome. Ref - https://github.com/angular/angularjs-batarang#console
This requires jQuery to be installed as well, but works perfectly for a dev environment. It looks through each element to get the instances of the scopes then returns them labelled with there controller names. Its also removing any property start with a $ which is what angularjs generally uses for its configuration.
let controllers = (extensive = false) => {
let result = {};
$('*').each((i, e) => {
let scope = angular.element(e).scope();
if(Object.prototype.toString.call(scope) === '[object Object]' && e.hasAttribute('ng-controller')) {
let slimScope = {};
for(let key in scope) {
if(key.indexOf('$') !== 0 && key !== 'constructor' || extensive) {
slimScope[key] = scope[key];
}
}
result[$(e).attr('ng-controller')] = slimScope;
}
});
return result;
}
in angular we get jquery element by angular.element().... lets c...
angular.element().scope();
example:
<div id=""></div>
Put a breakpoint in your code at a somewhere close to a reference to the $scope variable (so that the $scope is in the current 'plain old JavaScript' scope). Then your can inspect the $scope value in the console.