[英]How to call an angularjs function dynamically on 'ng-click' event?
I want to call a function dynamically as the function name string will come from database. 我想动态调用一个函数,因为函数名称字符串将来自数据库。 ie "myNameIsGopal". 即“ myNameIsGopal”。
Using window"myNameIsGopal", I am able to call a function which is not there in the controller, but I want to call a function inside angular controller dynamically. 使用窗口“ myNameIsGopal”,我可以调用控制器中不存在的函数,但是我想动态地调用角度控制器中的函数。
Right now, I have defined following function outside the controller, which I am able to call using window"myNameIsGopal" 现在,我已经在控制器外部定义了以下函数,我可以使用窗口“ myNameIsGopal”调用该函数
function myNameIsGopal(args){
alert(args);}
But I want to call a method like this from inside of the controller. 但是我想从控制器内部调用这样的方法。
$scope.myNameIsGopal=function(args){
alert(args);
};
Below is My html page: 以下是我的html页面:
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.16/angular.js" data-semver="1.3.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<input type="text" ng-model="value" ng-enter="hideToolTip(event)" />
<input type="button" ng-model="gobar" ng-click="dynamicCaller('myNameIsGopal','banana')" value="click me">`enter code here`
</body>
</html>
Below is App.js code: 以下是App.js代码:
var app = angular.module('plunker', []);
function myNameIsGopal(arg){
alert(arg);
}
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.dynamicCaller=function(arg1,arg2){
window[arg1](arg2);
}
$scope.myNameIsGopal=function(arg){
alert(arg);
}
$scope.hideToolTip = function(event) {
alert(event);
}
});
You were close, as function are defined in $scope
object use it not window
您已关闭,因为函数是在$scope
对象中定义的,请使用它而不是window
$scope.dynamicCaller=function(arg1,arg2){
$scope[arg1](arg2);
}
var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.dynamicCaller = function(arg1, arg2) { $scope[arg1](arg2); } $scope.myNameIsGopal = function(arg) { console.log(arg); } $scope.hideToolTip = function(event) { console.log(event); } });
<script src="https://code.angularjs.org/1.3.16/angular.js"></script> <div ng-app="plunker" ng-controller="MainCtrl"> <p>Hello {{name}}!</p> <input type="button" ng-click="dynamicCaller('hideToolTip', 'mango')" value="click hideToolTip"/> <input type="button" ng-click="dynamicCaller('myNameIsGopal','banana')" value="click myNameIsGopal"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.