34

Is it possible to call AngularJS controller function from console (Chrome Developer Tools console)?

e.g.

app.controller('AddCtrl', ['$scope', function ($scope) {



    $scope.save = function(){
        // do stuff here - call it from console
    };

}]);
Iladarsda
  • 10,640
  • 39
  • 106
  • 170

5 Answers5

33

Yes, you just need to use angular.element to get an element that's within the scope of your controller:

angular.element("yourElement").scope().save();
tymeJV
  • 103,943
  • 14
  • 161
  • 157
25

Open the browsers developer console. Inspect the element where the controller gets injected. Execute the following:

angular.element($0).scope().save()

$0 is the element you are currently selecting in the developer console elements panel.

GonchuB
  • 705
  • 5
  • 8
11

If you are only using angular and NOT using jquery you can do something like angular.element(document.getElementById('yourElement')).scope().save();

If you are using BOTH angular and jquery, you can do angular.element($('#yourElement')).scope().save(); assuming the the id attribute of your element is set like this <div id=yourElement></div>

VERY IMPORTANT But as noted here if the function you are calling from the console does anything such that you wish the changes to show up in the view then you have to pass them through $apply() like this

var scope = angular.element($('#story')).scope();
scope.$apply(function(){
  scope.showNextScene();
});
Community
  • 1
  • 1
Sumeet Pareek
  • 2,739
  • 2
  • 22
  • 17
1

You can load a Chrome Extension for developers called AngularJS Batarang.

It will add an AngularJS tab to the developer console.

Selecting an element in your page, if it has a $scope, it will show in the "Elements" right hand pane, under the "$scope" tab.

Craig Gjerdingen
  • 1,844
  • 1
  • 21
  • 21
  • As mentioned by others If jQuery is available, angular.element is just an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or jqLite. – Craig Gjerdingen Sep 07 '16 at 15:50
1
  1. In the Chrome inspector click on the element which is scope related to controller where you want to execute.
  2. Type angular.element($0).scope().nameYourFunctionInScope();
  3. Execute
redrom
  • 11,502
  • 31
  • 157
  • 264