繁体   English   中英

AngularJS调用带有函数的数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM