ruby-on-railsstimulusjs

Stimulus not geting values from html


I'm doing a basic controller and trying to get data from the HTML with the tag value.

The problem is that the data is always empty

<div data-controller="selectable">
  <div class="flex" data-selectable-iconurl="test" data-selectable-iconurl-value="test">
     something here
  </div>
</div>

Notice I did multiple combinations of the value tag ( from different posts) in order to verify if one is working.

Now when I try to access the values in the controller is always empty

// selectable_controller.js

import {Controller} from "@hotwired/stimulus"

export default class extends Controller {
  static values = {iconurl: String }

  connect() {
    console.log(this.iconurlValue)
  }

}

I double-checked the documentation and could not find why the value is not passed to the controller and is always empty


Solution

  • When Stimulus controller is on the same element as the value, you should be able to retrieve the value:

    <div data-controller="selectable" data-selectable-iconurl-value="test">
    

    If your value needs to be set on a child element, then I suggest to just access it the old way :

    console.log(this.element.querySelector("div.flex").dataset.selectableIconurlValue)
    

    Though your value may just be treated like a classic HTML element dataset attribute. You lose every Turbo goodness such as observing any change to the value : https://dev.to/borama/stimulus-2-0-value-change-callbacks-what-are-they-good-for-4kho

    Not sure why the required location of the value is not precised in the Stimulus Handbook. But the logic is having states on the Stimulus controller, just like what happens in different JS framework, so there is no reason to have the value elsewhere than on the controller anyway.