Zac Powell Zac Powell - 7 months ago 18
Javascript Question

Reload Jquery after ng-if change

I am working on a site that is making use of an ng-if statement to change elements in a form based on

<div class="column full">
<?php
echo $this->Form->input('company_type', array(
'type' => 'radio',
'options' => array(
'partnership' => 'Partnership',
'sole_trader' => 'Sole Trader',
'limited_company' => 'Limited Company'
),
'ng-model' => 'companyType',
'legend' => 'Company Type'
));
?>
</div>
<div ng-if="companyType == 'sole_trader'">
...
echo $this->Form->button('Find Address' , array('type' => 'button', 'id' => 'findTraderAddress'));
...
</div>
<div ng-if="companyType == 'partnership'">
...
echo $this->Form->button('Find Address' , array('type' => 'button', 'id' => 'findPartnerAddress'));
...
</div>
<div ng-if="companyType == 'limited_company'">
...
echo $this->Form->button('Find Address' , array('type' => 'button', 'id' => 'findCompanyAddress'));
...
</div>


My issue is I have some jQuery that needs to bind to these buttons, however the ng-if makes it so the jQuery only binds to which ever radio button is select on the page load. If you then change the radio button the new button shown does not have its function bound to it.

$('#findTraderAddress').click(function () {
console.log('clicked');
})
$('#findPartnerAddress').click(function () {
console.log('clicked');
})
$('#findCompanyAddress').click(function () {
console.log('clicked');
})


Is there a way to load the jQuery after the ng-if statement changes so the button click function gets bound as it should?

Answer

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.

General Syntax

$(document).on('event','selector',callback_function)

Example

$(document).on('click', "#findTraderAddress", function(){
     console.log('clicked');
});

In place of document you should use closest static container for better performance.

However, I would recommend you to use ngClick instead of binding event using jQuery.