Crabar
Crabar

Reputation: 1857

Passing argument on action in Ember

I have three toggle buttons in my "hbs" file. And I have "options" array in the controller related to this template. I want to update "options" whenever user selected/deselected any of buttons. For example, if button 1 selected and other not - "options" must be [1]. If second and third buttons selected and first not - "options" must be [2, 3].

And I tried to make this through actions with parameters:

<button {{action 'toggleOption' name aria-pressed}}
id="first-button" name="1" type="button" class="btn 
option-toggle-button" data-toggle="button" aria-pressed="false"
autocomplete="off">First button</button>

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({
    options: [],
    actions: {
        toggleOption(id, selected) {
            var options = this.get("options");

            if (selected) {
                if (options.contains(id))
                    options.push(id);
            } else {
                var index = options.indexOf(id);
                if (index >= 0)
                    options.splice(index, 1);
            }

            this.set("options", options);
        }
    }
});

But "toggleOption" was calling with "undefined" params so I assume that I on a wrong way.

Question: how can I implement needed logic? Maybe I need a completely different approach to solve this problem?

Upvotes: 0

Views: 167

Answers (1)

GUL
GUL

Reputation: 1195

You can use:

<button {{action 'toggleOption' "1"}} id="first-button" name="1" type="button" class="btn option-toggle-button" data-toggle="button" aria-pressed="false"autocomplete="off">First button</button>

<button {{action 'toggleOption' "2"}} id="first-button" name="1" type="button" class="btn option-toggle-button" data-toggle="button" aria-pressed="false"autocomplete="off">Second button</button>

where "1" and "2" are the values passed to the controller action. Then in the toggleOption action you can do your logic to add/remove value into options array

actions: {
    toggleOption(value) {
        // ...your logic here...
    }
}

Upvotes: 1

Related Questions