如何在AngularJS中调用函数作为动态字符串?

时间:2018-05-09 10:33:24

标签: javascript html angularjs scope angularjs-ng-click

如何在function assigned variable中使用 ng-click? ?我在下面尝试了三种方式,但这也无效。

你可以告诉我有可能吗?如果是,那怎么样?

var app = angular.module("app", []);
app.controller("name", function($scope) {

 $scope.showname = function()
 {
 alert("Ramesh");
 }
 
 $scope.variable1 = $scope.showname;
  
 $scope.variable2 = "showname()";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="name">
<button type="button" ng-click="variable1" tabindex="10003" >Not working 1 </button>

<button type="button" ng-click="$scope[variable2]()" tabindex="10003" >Not working 2 </button>

<button type="button"  ng-click="variable2" tabindex="10003" >Not working 3 </button>

<button type="button" ng-click="showname()" tabindex="10003"> working </button>
</div>

3 个答案:

答案 0 :(得分:0)

尝试:

<button type="button" ng-click="variable1()" tabindex="10003" >Now it'll work 1 </button>

Working plunkr

答案 1 :(得分:0)

$scope.showname有函数引用。所以只需将它分配给您的变量,如

$scope.variable1 = $scope.showname

然后拨打ng-click,如valiable1()

&#13;
&#13;
var app = angular.module("app", []);
app.controller("name", function($scope) {

 $scope.showname = function()
 {
 alert("Ramesh");
 }
 
  $scope.variable1 = $scope.showname;
  
  $scope.variable2 =  $scope.showname;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="name">
<button type="button" ng-click="variable1()" tabindex="10003" >Not working 1 </button>

<button type="button" ng-click="variable2()" tabindex="10003" >Not working 2 </button>

<button type="button"  ng-click="variable1()" tabindex="10003" >Not working 3 </button>

<button type="button" ng-click="showname()" tabindex="10003"> working </button>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

不使用$scope,而是使用this关键字:

  

<button type="button" ng-click="$scope[variable2]()" tabindex="10003" >
     Not working 2 
</button>

改为使用:

<button type="button" ng-click="this[variable2]()" tabindex="10003" >
     working
</button>

可以使用标识符this访问上下文对象。

有关详细信息,请参阅AngularJS Developer Guide - Expression context