如何在ng-click?
中使用function assigned variable
?我在下面尝试了三种方法,但这也不起作用。
你能告诉我是否有可能吗???如果是,那怎么做?
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>
您可以使用$scope.$eval
方法并像variable2()
一样调用该函数。
$eval
方法不计算 JavaScript;它们只评估AngularJS
表达式。
另外,对于以下行
$scope.variable1 = $scope.showname;
您只是保留对showname
函数的引用。你必须调用它
<button type="button" ng-click="variable1()" tabindex="10003" >Not working 1 </button>
var app = angular.module("app", []);
app.controller("name", function($scope) {
$scope.showname = function()
{
alert("Ramesh");
}
$scope.variable1 = $scope.showname;
$scope.variable2 = $scope.$eval("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="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>
尝试:
<button type="button" ng-click="variable1()" tabindex="10003" >Now it'll work 1 </button>
工作 plunkr
$scope.showname
具有函数引用。因此,只需将其分配给您的变量,例如
$scope.variable1 = $scope.showname
然后像valiable1()
一样点击 ng
var app = angular.module("app", []);
app.controller("name", function($scope) {
$scope.showname = function()
{
alert("Ramesh");
}
$scope.variable1 = $scope.showname;
$scope.variable2 = $scope.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="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>
不使用$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 开发者指南 - 表达式上下文。