Donny Gunawan Donny Gunawan - 5 months ago 13
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

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.

Comments