praveenpds
praveenpds

Reputation: 2936

How to trigger 'click ' event in Angular js

how to migrate the below function of jquery to angular js ?

  $( "#foo" ).trigger( "click" );

Problem here is im planning to trigger submit button automatically when user fills some data in our application.

so as im from jquery background ,

thanks in advance.

Upvotes: 6

Views: 42991

Answers (5)

Gerben Rampaart
Gerben Rampaart

Reputation: 9945

$timeout(function() {
    angular.element(domElement).triggerHandler('click');
}, 0);

The $timeout is for breaking angular's $apply cycle.

Upvotes: 9

gkalpak
gkalpak

Reputation: 48211

Usually you don't submit a form in AngularJS. You send the data using an XHR and get a response in JSON.

Something like this:

VIEW

<form name="myForm" ng-submit="login(credentials)">

  <label>
    Username:
    <input type="text" ng-model="credentials.username" />
  </label>

  <label>
    Password:
    <input type="password" ng-model="credentials.password" />
  </label>

 <button type="submit">Login</button>

</form>

CONTROLLER

$scope.credentials = {};
$scope.login = function login(credentials) {
  var user = credentials.username;
  var pass = credentials.password;

  // Do some data validation
  if (!user || !pass) {
    $window.alert('Please, enter a username and a password!');
    return;
  }

  // Send the data and parse the response
  // (usually done via a Service)
  LoginService.login(user, pass);
};

See, also, this short demo.

Upvotes: 1

Terje Nyg&#229;rd
Terje Nyg&#229;rd

Reputation: 1257

If you f.eks have a button you need to use ng-click="myFunctionName()" on the button itself.

And in the script file you use myFunctionName = $scope.function(){ yourCode... }

If you care completely new to Angular... you should read up a bit on it, since it basically stays away from the DOM, takes "control" over your webpage, and needs ng-app, ng-controller and uses $scope to hold states for content and data.

Upvotes: -2

Ferox
Ferox

Reputation: 582

$scope.triggerClick = function () {
  $timeout(function() {
    angular.element('#foo').trigger('click');
  }, 100);
};

The $timeout will run an $apply to the cycle if necessary.

Upvotes: 16

s.alem
s.alem

Reputation: 13079

Instead of that, you could use ng-change and call the submit function from your controller. Something like this:

<input type="text" ng-model="userData.field1" ng-change="mySubmitFunction(userData)">

Upvotes: -1

Related Questions