Reputation: 167
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.
Upvotes: 11
Views: 12319
Reputation: 19
This syntax seems working well
<button ng-click="this[method(param)]">{{ title }}</button>
starting from the suggestion of user dfsq and as the suggestion wasn't working with angularjs 1.6.4, I put the closing braket after the param value.
Upvotes: 1
Reputation:
This didn't work for me.. and..
I didn't want to deal with having html code in my angular app, or directives, or the use of eval. so I just wrapped my existing functions in a function:
$scope.get_results = function(){
return {
message: "A message",
choice1: {message:"choice 1 message", f: function(){$scope.alreadyDefinedFunction1()}},
choice2: {message:"choice 2 message", f: function(){$scope.alreadyDefinedFunction2()}},
};
}
in a different function:
$scope.results2 = $scope.get_results();
Snippet of use in html:
<ul class="dropdown-menu scroll-div">
<li><a ng-click="results2.choice1.f()">{{results_2_menu.choice1.message}}</a></li>
<li><a ng-click="results2.choice2.f()">{{results_2_menu.choice2.message}}</a></li>
</ul>
Was based on this js fiddle: http://jsfiddle.net/cdaringe/FNky4/1/
Upvotes: 2
Reputation: 193301
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.
Upvotes: 30