简体   繁体   中英

Invoking an Angular click event from browser console

I'm inspecting the DOM on an Angular application and seeing a simple link such as the following:

<button type="button" class="button mini text right clear-all" ng-show="draft.roster.slotsFilled" ng-click="draft.resetRoster()" really="Are you sure you want to clear all players from your team?">

I wanted to try to invoke the ng-click command here directly into the browser console by simply pasting draft.resetRoster(); Unfortunately I'm getting draft is not defined when trying to access it through the console. The link works perfectly fine itself though.

What's the best way to access/invoke the code that the ng-click attribute is referencing here?

ng-click just registers a click event only so you could literally fire a click event from console by selecting the element. Example:-

Say your button can be uniquely identified by all these css classes, you could do:

//You could use jquery as well if it is available, here some vanilla accessors.
document.querySelector('.button.mini.text.right.clear-all').click();
//If you have multiple, use querySelectorAll and 
//select the respective element or if you have an Id:
document.getElementById('#myButton').click();

or you can use extensions like batarang (chrome) to access the scope directly or get the scope of the element using

angular.element(elementRefGotFromOneOfTheAboveWays).scope().draft.resetRoster();`

and if you want to see change reflected in DOM you would need to call scope.$apply() manually, ie

var scope = angular.element(elementRefGotFromOneOfTheAboveWays).scope();
scope.draft.resetRoster();
scope.$apply();

Using Chrome, install the angular batarang extension , then simply right click on the element, click "Inspect element" and in the console type:

$scope.draft.resetRoster()

If you have methods in an angular service that you'd like to call, you can access the service by doing:

service = angular.element(document).injector().get('NameOfServiceHere')
service.somePropertyOrMethod()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM