javascript – How do I simulate a click on an element when clicking on another element in angularjs-ThrowExceptions

Exception or error:

I have a weird request. When I click one button, I want it to click another button programmatically. Is there a way to do this in angularjs?

Here’s what I have tried:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.clickButton = function(){
    angular.element(document.getElementById('buttonToBeClicked')).triggerHandler('click')
  }
  
  $scope.alert = function(){
    alert("I was clicked programmatically")
  }
});
AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">

<button id="buttonToClick" ng-click="clickButton">button to click</button>
  
<button ng-click=alert() id="buttonToBeClicked">button to be clicked</button>

</div>

For full context, I am trying to create a button that clicks all buttons on a page.

How to solve:

What you have will work with one small fix:

<button id="buttonToClick" ng-click="clickButton">button to click</button>

Should be:

<button id="buttonToClick" ng-click="clickButton()">button to click</button>

You were missing the parens on the method in your ng-click directive. Here’s a working sample:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.clickButton = function() {
    angular.element(document.getElementById('buttonToBeClicked')).triggerHandler('click')
  }

  $scope.alert = function() {
    alert("I was clicked programmatically")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">
  <button id="buttonToClick" ng-click="clickButton()">button to click</button>
  <button id="buttonToBeClicked" ng-click="alert()">button to be clicked</button>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *