[英]AngularJS calling array with function
我正在嘗試使用angularjs創建上下文菜單。當用戶單擊右鍵時,上下文菜單將打開,但是上下文菜單可能會根據用戶級別而有所不同,因此我想使用功能調用'mycontext'菜單數組,但當我用角度控制器中的功能來稱呼它。
我想用“ launch()”函數調用上下文菜單。
<a ng-context-menu="launch(y)">Open Context Menu</a>
我的控制器:
controller: function($scope) {
$scope.launch = function (m) {
// .......................
$scope.mycontext = [
[
'opt1',
function () {
console.log("buy");
}
], [
'opt2',
function () {
console.log("sell");
}
]
];
};
}
如何使用調用函數運行它?
我認為您想要一個帶有JSON對象的數組。
var test = [
{
someValue:'tada',
someFunct: function() {
alert('tada!');
}
},
{
someValue:'something else',
someFunct: function() {
alert('something else here');
}
}];
我使用簡單的jQuery制作了一個示例,但應輕松地將其應用於Angular代碼。 http://jsfiddle.net/fan4Lwu4/
看起來您想調用$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>
或者,如果可以更改數組本身,請使用立即調用函數表達式。
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.