2014-05-07 161 views
0

我是新來的角js和仍然工作的東西。我想問一下在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'); 
    }; 
}); 

如果目前還不清楚請你告訴我。

+0

你是什麼意思的「發起」ng點擊? – Brocco

+0

您需要使用'data-ng-click =「menu.mode()」',但mode屬性應該指向一個函數。在你的情況下,我把它看作一個字符串變量。 – Chandermani

回答

1

在你的控制,當你定義的菜單列表排列,不設置模式爲一個字符串,而是以實際功能

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

然後在您的標記:

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

這裏一個link到工作代碼

0

定義函數,然後將它們分配給對象。將它們分配爲

$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/

+0

感謝那個我正在尋找的人! :) – loki9