How to call Jquery function by angular ng-click?

I have a javascript function which I’d like to call by on click using angular JS 1.X

this function is using Jquery


function AccountInformation(){
$("#Edit_Info_Btn").on('click', function() {
        //$(this).parents().find('ul.breadcrumb li:first-child').remove();
        $(this).parents().find('ul#breadcrumbCustomer').append('<li>Edit Account Information</li>');        
		$("#Manage_Customer").hide();
		$("#Customer_Details").show();
		$('.nav-tabs a[href="#AccountTabContent"]').tab('show');
		$("#EditAccount").show();
});
}

How to call this function by angular ng-click . What is the way ?
I’m using angular js 1.3 version

In your controller you’d have something like

$scope.handleClick = function () {
  // jQuery stuff
}

and in the corresponding template something like

<button id="Edit_Info_Btn" ng-click="handleClick()">Click me</button>

That said (and sorry for repeating myself), I would strongly suggest not to mix AngularJS and jQuery like this; not only is there rarely a point in doing so, but it can likely break your application. A core idea of AngularJS is that you do not have to manipulate the DOM manually; instead, you can solve most things with directives via scope. E.g. something like this

$("#Edit_Info_Btn").on('click', function() {
  $("#EditAccount").show()
})

might look like this the AngularJS way:

// In the controller
$scope.showEditAccount = false

$scope.handleClick = function () {
  $scope.showEditAccount = true
}
<!-- template -->
<div ng-show="showEditAccount">Some form elements</div>
<button ng-click="handleClick()">Click me</button>

Or even just

<!-- template w/o additional controller logic -->
<div ng-show="showEditAccount">Some form elements</div>
<button ng-click="showEditAccount = true">Click me</button>

If you’re looking for a framework that goes well with jQuery, you might have a look at backbone.js. It’s a bit of a dinosaur among the JS frameworks, but then again, so is AngularJS. :-P

1 Like

show/hide is fine.

there is append in DOM in Jquery like below

$(this).parents().find('ul#breadcrumbCustomer').append('<li>Edit Account Information</li>');

How do you do that in your Angular handleClick() method ?

Well that’s hard to tell without seeing your code… if that ul#breadcrumbCustomer is part of the same component, it works exactly as shown above. If it is part of another component, it depends on the relation of the two: if it’s a child component, it will inherit from that parent $scope automatically; otherwise you can $broadcast an event, or communicate with the other component via a dedicated service.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.