I am creating an application where the site menu would be dynamically loaded from JSON file. Each menu may correspond to an action that would be defined inside the ng-click
directive. This would look something like this
<li ng-repeat="menuItem in menuContainer.menus" class="{{menuItem.cssClass}}">
<a href="{{menuItem.url}}" ng-click="{{menuItem.clickAction}}">
<i class="{{menuItem.iconClass}}"></i>{{menuItem.name}}
<span class="badge">{{menuItem.subMenus.length}}</span>
</a>`enter code here`
<li>
Now the problem is ng-click
does not recognize the clickAction
as a function, I believe this is due to linking process. I want to know is there any way to evaluate a string to method. I tried do $eval
but it executes the function on load.
How do I do this?
Define methods not as strings, but as functions and replace
ng-click="{{menuItem.clickAction}}"
tong-click="menuItem.clickAction()"
. Another way to define function on $scope, like:and replace your ng-click to
ng-click="executeString(menuItem.clickAction)"
. Anyway, use eval is antipattern;)Remember, that
ng-click
and other directives, like that, takes angular expression as parameter. And if body of you expression isa = b + c
than angular convert it in javascript like$scope.a = $scope.b + $scope.c