首页 > 解决方案 > 如何将 amp-selector 的文本内容设置为 amp-state

问题描述

我想知道如何根据用户选择并将其设置为的选项获取文本内容amp-state。例如,如果用户选择“红色”选项。我想将“胭脂”设置amp-state为非“红色”。我知道我可以value通过 setState 函数中的 event.targetOption 获得。但是,找不到如何获取文本并将其设置为amp-state.

<amp-state id="selectedColor">
    <script type="application/json">
    {
        "value": ""
    }
    </script>
</amp-state>

<p>Selected Color <span [text]="selectedColor.value"></span></p>

<amp-selector
  layout="container"
  on="select:AMP.setState({
        selectedColor: {
          value: event.targetOption
        }
      })">
  <div option="red">rouge</div> <!-- user select this -->
  <div option="blue">bleu</div>
  <div option="green">vert</div>
</amp-selector>

我的预期输出如下

<p>Selected Color <span>rouge</span></p>

不是

<p>Selected Color <span>red</span></p>

标签: amp-htmlamp-bind

解决方案


你可以这样做:

<!-- 1. Initialize colorMap -->
<amp-state id="colorMap">
  <script type="application/json">
    {
      "red": "rouge",
      "blue": "bleu",
      "green": "vert"
    }
  </script>
</amp-state>

<!-- 2. On select: set new state of selectedColor -->
<amp-selector
  layout="container"
  on="select:AMP.setState({selectedColor: event.targetOption})">
  <div option="red">rouge</div>
  <div option="blue">bleu</div>
  <div option="green">vert</div>
</amp-selector>

<!-- 3. Bind the selectedColor value as identifier for the colorMap -->
<p>Selected Color <span [text]="colorMap[selectedColor]"></span></p>
  1. 初始化colorMap为预定义<amp-state>
  2. 选择时:将新状态设置selectedColor为单个字符串(不是具有键:值的对象)
  3. 将值绑定selectedColorcolorMap

注意颜色图和选择器的值必须一致。我更喜欢使用模板引擎。


推荐阅读