With angularjs, how can I trigger a click, or is there a better way?

user1447679 picture user1447679 · Apr 27, 2015 · Viewed 18.6k times · Source

I'm creating a form wizard with AngularJS.

Think of each fieldset like so:

<div ng-controller="MyController as fs">
  <fieldset>
      ...
      <button ng-click="fs.StepForward($event)">Next</button>
  </fieldset>

  <fieldset>
      ...
      <button ng-click="fs.StepBackward($event)">Previous</button>
      <button ng-click="fs.StepForward($event)">Next</button>
  </fieldset>
</div>

What I've done is, in my controller found the current fieldset and the next fieldset like so:

app.controller("MyController", function() {
  var ft = this;
  ft.StepForward = function(event) {
    // It's here that I need to find the fieldset
    ft.current_fs = event.currentTarget.parentNode;
    ft.next_fs = event.currentTarget.parentNode.nextElementSibling;
  }
});

So first, I'm not sure if this is the absolute best way to do it, but it works.

Down to my main question... Inside of one of the fieldsets I have some li elements, and if certain elements are clicked, I want to trigger a click on the NEXT button automatically.

I tried adding an ng-click:

<fieldset>
  <ul>
    <li><a ng-click="fs.TriggerClick($event)">Some Itme</a></li>
  </ul>
  <button id="MyButtonTest" ng-click="fs.StepForward($event)">Next</button>
</fieldset>

app.controller("MyController", function() {
  var ft = this;
  ft.StepForward = function(event) {
    // It's here that I need to find the fieldset
    ft.current_fs = event.currentTarget.parentNode;
    ft.next_fs = event.currentTarget.parentNode.nextElementSibling;
  }

  ft.TriggerClick = function(event) {
    angular.element('#MyButtonTest').trigger('click');
  }
});

But when I created a function to trigger a click on the button, I got the error:

Error: $rootScope:inprog Action Already In Progress

So I'm wanting to reach to jQuery, but I'm sure there's an angular way of doing this.

Answer

jbigman picture jbigman · Apr 27, 2015

You have to break out of the current $apply() cycle. One way to do this is using $timeout() (See why)

Try this:

<fieldset>
  <ul>
    <li><a ng-click="triggerClick()">Some Item</a></li>
  </ul>
  <button id="MyButtonTest" ng-click="fs.StepForward($event)">Next</button>
</fieldset>

Controller

$scope.triggerClick = function(){
    $timeout(function() {
        angular.element('#MyButtonTest').triggerHandler('click');
    }, 0);
}