You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
by manually adding a file in the controllers directory of your Rails application, e.g., app/javascript/controllers/my_feature_controller.js.
The controller file should define your Stimulus controller class. The connect action gets run as soon as an element connected to your controller is initialized:
In your HTML view, use the data-action attribute to associate the action with an event. The syntax is data-action="<name-of-your-controller>#<nameOfTheAction>":
In your controller, use the targets property to define named references to HTML elements. You can then access those element using this.<targetName>Target:
In your HTML view, use the data-target attribute to indicate where the element should be referenced. The syntax is data-target="<name-of-your-controller>.<target-name>:
In your controller, use the values property to define named references to dynamic values, and specify their datatype. They become accessible in your controller using this.<valueName>Value:
// app/javascript/controllers/my_feature_controller.jsimport{Controller}from"stimulus";exportdefaultclassextendsController{staticvalues={greeting: String};connect(){console.log("MyFeatureController connected!");}initialize(){console.log("Initialized with greeting:",this.greetingValue);}}
In your HTML view, use the data-value attribute to set the dynamic value on the same element your controller is connected to. The syntax is data-<name-of-your-controller>-<name-of-the-value>-value="The value you want inside":
<divdata-controller="my-feature" data-my-feature-greeting-value="Hello from data-value!"><!-- Content here --></div>