简体   繁体   中英

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.

i want to call my context menu with 'launch()' function.

<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.

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. 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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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