2015-05-15 22 views
8

我有按钮,这样作出动态函数NG单击

<button ng-click="method = 'create'; title = 'Create'>create</button> 
<button ng-click="method = 'update'; title = 'Update'>update</button> 

以上这

<button ng-click="create(param)">{{ title }}</button> 
<button ng-click="update(param)">{{ title }}</button> 

代码工作正常,但我想让它充满活力。

所以我改变它如下。

<button ng-click="{{ method }}(param)">{{ title }}</button> 

这是不行的,我不知道为什么,但如果我做检查元素,上面的代码生成如前所述纠正代码。

回答

24

使用bracket notation

<button ng-click="this[method](param)">{{ title }}</button> 

this点到目前的范围对象,以便与this[method]您可以通过访问变量名的方法。

+1

刚刚创建了一个Plnkr http://plnkr.co/edit/aWIS1oHja11hGm4pycMC?p=preview –

+0

thx u非常,好友^ _^ –

2

这并没有为我工作..和..

我不想处理有我的角度应用程序,或指令,或使用eval HTML代码。所以我刚刚结束我的现有功能于一身的功能:

$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()}}, 
     }; 
} 

在不同的功能:

使用
$scope.results2 = $scope.get_results(); 

片段中的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> 

正是基于此js的小提琴: http://jsfiddle.net/cdaringe/FNky4/1/

+0

这对我有效!但接受的答案并没有。谢谢 – JoeCodeCreations

0

该句法看起来效果不错

<button ng-click="this[method(param)]">{{ title }}</button> 

从用户dfsq的建议开始,并且由于该建议与angularjs 1.6.4不兼容,我将关闭框放在参数值之后。