Donny Gunawan Donny Gunawan - 2 years ago 78
AngularJS Question

Make a dynamic function on ng-click

I have button like this

<button ng-click="method = 'create'; title = 'Create'>create</button>
<button ng-click="method = 'update'; title = 'Update'>update</button>

and this

<button ng-click="create(param)">{{ title }}</button>
<button ng-click="update(param)">{{ title }}</button>

Code above works fine, but I want to make it dynamic.

so I change it like following.

<button ng-click="{{ method }}(param)">{{ title }}</button>

This does not work, I dont know why, although if I do inspect element, code above generates corrects code as mentioned before.

Answer Source

Use of bracket notation:

<button ng-click="this[method](param)">{{ title }}</button>

this points to current scope object so with this[method] you can access method via variable name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download