通过数组传递函数

时间:2014-05-07 04:11:55

标签: angularjs angularjs-ng-repeat

我是棱角分明的新手并且还在做事。我想问一下是否可以在角度js中启动ng-click变量(哪些是函数。)?这是我的代码片段

<div data-ng-controller="DeathRayController">
    <button data-ng-click="toggleMenu()">Toggle Menu</button>
    <ul ng-show="menuState.show">
        <li data-ng-repeat="menu in menuList"><a href="" data-ng-click="menu.mode">{{ menu.value }}</a></li>
    </ul>
</div>

这是我的控制器使用angularjs:

var showHide = angular.module('showHide', []);

showHide.controller('DeathRayController', function ($scope) {
// the idea is to display this on the <a ng-click="menu.mode">
    $scope.menuList = [
        { mode: 'stun()', value : 'Stun' },
        { mode: 'disinegrate()' ,value : 'Disinegrate' },
        { mode: 'erase()', value : 'Erase' },
    ];
    $scope.menuState = { show: false };
    $scope.toggleMenu = function() {
        $scope.menuState.show = !$scope.menuState.show;
    };
    $scope.stun = function() {
        alert('Snorlax is stunned!');
    };
    $scope.disinegrate = function() {
        alert('Charizard used Disinegrate!');
    };
    $scope.erase = function() {
        alert('erased Sleep skill');
    };
});

如果还不清楚请告诉我。

2 个答案:

答案 0 :(得分:1)

在你的控制器中,当你定义menuList数组时,不要将mode设置为字符串,而是设置为实际的函数

$scope.menuList = [
    { mode: $scope.stun, value : 'Stun' },
    { mode: $scope.disinegrate ,value : 'Disinegrate' },
    { mode: $scope.erase, value : 'Erase' },
];

然后在你的标记中:

data-ng-click="menu.mode()"

这是工作代码link

答案 1 :(得分:0)

在将函数指定给object之前定义函数。将它们指定为

$scope.menuList = [
    { mode: $scope.stun, value : 'Stun' },
    { mode: $scope.disinegrate ,value : 'Disinegrate' },
    { mode: $scope.erase, value : 'Erase' },
]; 

并在html中使用它们

<ul>  
 <li data-ng-repeat="menu in menuList"><a href="" data-ng-click="menu.mode()">{{ menu.value }}</a></li>
</ul>

查看:

<div data-ng-controller="DeathRayController">
  <button data-ng-click="toggleMenu()">Toggle Menu</button>
  <ul ng-show="menuState.show">
    <li data-ng-repeat="menu in menuList"><a href="" data-ng-click="menu.mode()">{{ menu.value }}</a></li>
  </ul>
</div>

<强>控制器:

var showHide = angular.module('showHide', []);

showHide.controller('DeathRayController', function ($scope) {
// the idea is to display this on the <a ng-click="menu.mode()">
$scope.stun = function() {
    alert('Snorlax is stunned!');
};
$scope.disinegrate = function() {
    alert('Charizard used Disinegrate!');
};
$scope.erase = function() {
    alert('erased Sleep skill');
};
$scope.menuList = [
    { mode: $scope.stun, value : 'Stun' },
    { mode: $scope.disinegrate ,value : 'Disinegrate' },
    { mode: $scope.erase, value : 'Erase' },
];
$scope.menuState = { show: false };
$scope.toggleMenu = function() {
    $scope.menuState.show = !$scope.menuState.show;
};    

});

小提琴:http://jsfiddle.net/rVCV2/1/