Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 711
user1447679 Avatar asked Apr 27 '15 16:04

user1447679


1 Answers

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);
}
like image 177
jbigman Avatar answered Oct 14 '22 15:10

jbigman