角JS NG单击操作函数的字符串 [英] Angular JS ng-click action function as string

查看:109
本文介绍了角JS NG单击操作函数的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建所在部位菜单将从JSON文件动态加载的应用程序。每个菜单可以对应于将在 NG-点击指令内部定义的动作。这将是这个样子

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>

现在的问题是 NG-点击不承认 clickAction 作为一个功能,我相信这是由于在连接的过程。我想知道有没有什么办法来评估一个字符串的方法。我试着做 $ EVAL ,但它执行负载的功能。

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.

我如何做到这一点?

推荐答案

定义方法不是字符串,但由于功能和替换 NG-点击={{menuItem.clickAction}} NG-点击=menuItem.clickAction()。另一种方式来定义的范围$功能,如:

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);
};

和更换您的NG-点击 NG-点击=executeString(menu​​Item.clickAction)。总之,使用eval是反模式;)

and replace your ng-click to ng-click="executeString(menuItem.clickAction)". Anyway, use eval is antipattern;)

记住, NG-点击及其他指令,这样,采用棱角分明的前pression作为参数。如果你身前pression是 A = B + C 比角度转换它在JavaScript像 $ scope.a = $范围。 b + $ scope.c

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

这篇关于角JS NG单击操作函数的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆