nightowl
nightowl

Reputation: 120

Writing functions for multiple buttons

I'm pretty sure I'm doing this 100% wrong, but I have three buttons that toggle separate functions. I'm trying to determine the best way to write the functions in my controller.

The buttons:

<button ng-class="{selected:vm.selectedOption==='1'}" ng-click="vm.selectOption('1')">1</button>
<button ng-class="{selected:vm.selectedOption==='2'}" ng-click="vm.selectOption('2')">2</button>
<button ng-class="{selected:vm.selectedOption==='3'}" ng-click="vm.selectOption('3')">3</button>

My methods:

vm.selectOption = function(1) {
   // function
};
vm.selectOption = function(2) {
   // function
};
vm.selectOption = function(3) {
   // function
};

or

vm.selectOption = function(option) {
 if (vm.selectedOption==='1') {
   // function
 };
 if (vm.selectedOption==='2') {
   // function
 };
 if (vm.selectedOption==='3') {
   // function
 };
};

or I imagine there is a more correct way to do this that I'm not seeing.

Upvotes: 1

Views: 371

Answers (1)

Lex
Lex

Reputation: 7194

You are passing the option to select to the function so:

vm.selectOption = function(option) {
    vm.selectedOption = option;
}

If you are looking to do something specific based on the option you just set:

vm.selectOption = function(option) {
    vm.selectedOption = option;
    switch(option) {
        case '1':
            // do something
            break;
        case '2':
            // do something else
            break;
        case '3':
            // do something completely different
            break;
    }
}

Upvotes: 2

Related Questions