...

/

Adding Our First Controller

Adding Our First Controller

Add a controller to the application in this lesson.

How controllers work

The first thing we’re going to do with Stimulus is, create a “Show/Hide” button that will toggle the contents of the favorite concerts block on our page.

The bulk of our Stimulus code will go into a controller. Similar to our Rails controller, a Stimulus controller is where we store responses to events. But, Stimulus controllers are different in that they have less structure and fewer expectations than a Rails controller.

To invoke a controller, we add an attribute named data-controller to a DOM element on our page. The value of the attribute is the name of the controller. If we add an attribute data-controller="toggle", then Stimulus attaches it to a ToggleController, which it expects will be at controllers/toggle_controller.ts (or .js).

If the controller’s name is more than one word, we use dash case, so it would be ...