[Solved-6 Solutions] Scope variable using Angular JS - javascript tutorial



Problem:

How to access the $scope variable in browser’s console using Angular JS ?

Solution 1:

Just assign $scope as a global variable.

app.controller('myCtrl', ['$scope', '$http', function($scope, $http) {
    window.$scope = $scope;
}

Solution 2:

Then we can just write :

$scope

Read Also

let and var

Solution 3:

Select an element in the HTML panel of the developer tools and type this in the console :

angular.element($0).scope()
  • In WebKit, $0 is a reference to the selected DOM node in the elements tab, so by doing this we get the selected DOM node scope printed out in the console.
  • We can also target the scope by element ID, like this:
angular.element(document.getElementById('yourElementId')).scope()

Addons/Extensions

There are some useful Chrome extensions that we might want to check out:

  • Batarang - This has been around for a while.
  • ng-inspector - This is the newest one, and it allows to inspect your application's scopes.

jQuery Lite

If we load jQuery before AngularJS, angular.element can be passed a jQuery selector. So we could inspect the scope of a controller with

angular.element('[ng-controller=ctrl]').scope()
angular.element('button:eq(1)').scope()

We need to use a global function to make it easier:

window.SC = function(selector){
    return angular.element(selector).scope();
};
Now we could do this
SC('button:eq(10)')
SC('button:eq(10)').row   // -> value of scope.row

Solution 4:

Here to access the scope variable without Batarang extension :

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

To find your scope by controller name, we can do this:

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

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

scope.$apply();

Solution 5:

  • The best solution is Batarang with it's $scope after selecting an object (it's the same as angular.element($0).scope() or even shorter with jQuery: $($0).scope())
  • Additionally, we have main scope on the body element, a $('body').scope() works fine.

Solution 6:

If you can use your controller, the scope objects will be in the object in the returned object from scope().
For example, if your controller directive is created like this:

<div> ng-controller="FormController as frm"</div>

To access a startDate property of your controller, we would call angular.element($0).scope().frm.startDate


Related Searches to Scope variable using Angular JS - javascript tutorial