5

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

Nonyck
  • 652
  • 1
  • 12
  • 28

1 Answers1

5

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").dataset.selectableIconurlValue)

Though your value may just be treated like a common JS dataset component. You lose every Turbo goodness such as a mutation observer 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. Maybe I am wrong too and there is a way to have it acknowledged by Stimulus...

Maxence
  • 2,029
  • 4
  • 18
  • 37
  • So good, thanks - I had the same problem that I couldn't pass values into my Stimulus controller the official way, so followed your advice but its on the top element so just.. this.element.dataset.selectableInconurlValue – Node Noodler Jun 28 '23 at 10:01