Stimulus Discourse

.data-if (similar to ng-show)

#1

ng-if, ng-show and ng-repeat were my favorite part of angular, so I tried to make something similar : ) (obviously contrived example but it works fine):

A simple “data-if” I just did :) (obviously can be improved a lot)

class window.Data extends Stimulus.Controller
  connect: ->
    @value = @element.querySelector('[data-action]').value
    @update()

  change: (event) ->
    @value = event.target.value
    @update()

  update: ->
    @element.querySelectorAll('[data-if]').forEach (dataIf) =>
      if @value == dataIf.dataset.if
        dataIf.style.display = 'block'
      else
        dataIf.style.display = 'none'

window.application.register 'data', window.Data
usage looks like this (generated with slim/rails):

usage:

div(data-controller="data")
  = options_tag :value, ['hmmm', 'haha'], "data-action": "data#change"
  div(data-if="hmmm")
    p hmmmm
  div(data-if="haha")
    p very funny

(edit: hmm seeing many issues with this aproach, may be using an explicit target, maybe named targets :slight_smile: )

0 Likes