1

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.

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

So, I understand that part, but how do I then set functions based on the different options?
If I'm understanding what you're asking then my update should apply. If not, could you explain a little more what you're after?
Switch! I knew I was missing something obvious. This is exactly what I was looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.