[英]AngularJS calling array with function
i'm trying to create a context menu with angularjs.when users click right , context menu will open , however context menu may change according to user level,therefore i want to call 'mycontext' menu array with function but it does not work when i call it with function in controller in angular. 我正在尝试使用angularjs创建上下文菜单。当用户单击右键时,上下文菜单将打开,但是上下文菜单可能会根据用户级别而有所不同,因此我想使用功能调用'mycontext'菜单数组,但当我用角度控制器中的功能来称呼它。
i want to call my context menu with 'launch()' function. 我想用“ launch()”函数调用上下文菜单。
<a ng-context-menu="launch(y)">Open Context Menu</a>
My controller : 我的控制器:
controller: function($scope) {
$scope.launch = function (m) {
// .......................
$scope.mycontext = [
[
'opt1',
function () {
console.log("buy");
}
], [
'opt2',
function () {
console.log("sell");
}
]
];
};
}
How can i run it with calling function? 如何使用调用函数运行它?
I think you want an array with JSON objects. 我认为您想要一个带有JSON对象的数组。
var test = [
{
someValue:'tada',
someFunct: function() {
alert('tada!');
}
},
{
someValue:'something else',
someFunct: function() {
alert('something else here');
}
}];
I made an example with simple jQuery, but it should easily be adopted to your Angular code. 我使用简单的jQuery制作了一个示例,但应轻松地将其应用于Angular代码。 http://jsfiddle.net/fan4Lwu4/ http://jsfiddle.net/fan4Lwu4/
Looks like you want to invoke the functions inside $scope.mycontext
array, you can write a loop and invoke the functions. 看起来您想调用$scope.mycontext
数组中的函数,可以编写一个循环并调用这些函数。
angular .module('demo', []) .controller('DefaultController', DefaultController); function DefaultController() { var vm = this; vm.run = run; function run() { vm.mycontext = [ [ 'opt1', function () { console.log("buy"); } ], [ 'opt2', function () { console.log("sell"); } ] ]; for (var i = 0; i < vm.mycontext.length; i++) { vm.mycontext[i][1](); } } }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="demo"> <div ng-controller="DefaultController as ctrl"> <button type="button" ng-click="ctrl.run()">Run</button> </div> </div>
Or use Immediately Invoked Function Expressions if you can change the array itself. 或者,如果可以更改数组本身,请使用立即调用函数表达式。
angular .module('demo', []) .controller('DefaultController', DefaultController); function DefaultController() { var vm = this; vm.run = run; function run() { vm.mycontext = [ [ 'opt1', (function () { console.log("buy"); })() ], [ 'opt2', (function () { console.log("sell"); })() ] ]; } }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="demo"> <div ng-controller="DefaultController as ctrl"> <button type="button" ng-click="ctrl.run()">Run</button> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.