1

I have tried many ways to click a button on click of other button of AngularJS.

Dom element:

<a class="nav-bar-link" ng-click="someMethod()">

Button:

<a class="button">Log in</a>

Expected results

On click of button nav-bar-link should be clicked.


Attempted Solutions

$(document).on('click', '.button', function(event) {
  console.log('came');
  event.preventDefault();
  $(".nav-bar-link").click();
});
$(document).on('click', '.button', function(event) {
  console.log('came');
  event.preventDefault();
  $(".nav-bar-link").triggerHandler('click');;
});
$(document).on('click', '.button', function(event) {
  console.log('came');
  var a = $('nav-bar-link')[0];
  var e = document.createEvent('MouseEvents');
  e.initEvent('click', true, true);
  a.dispatchEvent(e);
});
$(".button").click(function() {
  setTimeout(function() {
    $('.nav-bar-link').trigger('click');
  }, 100);
  return false;
});

These answers were tested from browser console.

Please let me know if there is any solution to trigger the click. Nothing worked from the above solutions.

I would also accept both jQuery and JavaScript solutions.

2
  • If you are using Angular why aren't you doing $scope.someMethod = fucntion() {}? Commented Aug 4, 2016 at 15:59
  • there is an $scope functon written in angular JS and I am trying to attempt to trigger a click on the function when click happened on the other element. I just need a way to enable the trigger using Jquery. Note: Jquery perfectly works fine in the broswer. Why I am not able to trigger the click event in the DOM Commented Aug 4, 2016 at 16:06

1 Answer 1

3

You should specified type of selector, in your case .nav-bar-link, change

$("nav-bar-link").click(); 

by

$(".nav-bar-link").click(); 

UPDATED

You do not need to write much code to call an event, if you use angular you can use triggerHandler:

$(document).on('click', '.button', function(event) { 
     console.log('came'); 
     angular.element('.nav-bar-link').triggerHandler('click');
});

Result: https://jsfiddle.net/cmedina/4pkdros9/

Sign up to request clarification or add additional context in comments.

6 Comments

updated the question . editing was problem. Can you please check now
I dnt understand your jsfiddle since there is no angular JS implementation.
.nav-bar-link ng-click funtion written in angular js. I dnt think ur answer will work. you are writting seperate function call with jquery
I cannot use angular methods since I am trying to trigger the click from third party application, I can only use jquery . But the triggered element has angular method. To be precise I need : jquery click event on angular js DOM.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.