WastedSpace
WastedSpace

Reputation: 1143

Is it possible to pass a function name from json and apply to ng-click?

I'm building a dynamic nav bar in AngularJS, and I'm wondering if it is possible to have a function name as a string in the json and place it in an ng-click directive (and make it work)? So far this doesn't work...

In JSON:

"name":"Test Link",
"action":"testAction()"

In HTML:

<li ng-repeat="link in navlinks"><a ng-click="link.action">{{link.name}}</a></li>

I realise there are other ways of doing this, such as routing & even something like ng-click="genericFunction({{link.action}})"(?). Just interested if it is possible to pass a function from json to ng-click.

Thanks!

Upvotes: 1

Views: 417

Answers (1)

jcubic
jcubic

Reputation: 66590

You can use $eval for that, it will evalutate expression:

$scope.foo = function() {
    alert('x');
};

$scope.json = {
    fn: "foo()"
};

And in html:

<button ng-click="$eval(json.fn)">click</button>

Upvotes: 3

Related Questions