Angular JS ng-click action function as string

2019-07-25 23:07发布

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?

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-25 23:49

Define methods not as strings, but as functions and replace ng-click="{{menuItem.clickAction}}" to ng-click="menuItem.clickAction()". Another way to define function on $scope, like:

$scope.executeString = function(body){
  eval(body);
};

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 is a = b + c than angular convert it in javascript like $scope.a = $scope.b + $scope.c

查看更多
登录 后发表回答