简体   繁体   中英

Reference text content of current event with Google AMP “on” action

I am trying to rewrite our stack to be AMP valid

I have the following pattern :

  1. A search bar is available to type in a query.
  2. When you type text (input-debounce), an amp-list is shown (unhidden) and a new state variable searchQuery is created with the content of event.value (the search bar input value)
  3. A call is made to endpoint A by an amp-state component (with searchQuery as a parameter)
  4. The results are displayed in the amp-list as links with some text content (let's call it title ) and a blank href ( # )

Now what I would like is that when you click a result from the list, the value of the search input be set the value of the clicked element. Like an autocomplete/selector of some sort.

What I tried is having an on attribute on each list item with tap:AMP.setState({searchQuery: event.value})

But when I click a result, the search bar value is always set to null .

I tried : event.value event.target.value event.innerHTML event.innerContent event.text Also tried replacing the link ( a ) to a span a button and such, same result.

Is this actually possible with AMP ?

You have to bind the input element's value to searchQuery for this to work. Here is a simplified sample (without an amp-list):

  <input type=text [value]=searchQuery on="input-debounced:AMP.setState({searchQuery: event.value})">

  <button on="tap:AMP.setState({searchQuery: 'test'})">
    Click
  </button>
  <div [text]=searchQuery></div>

I did not find a way to access the element value of the needed item directly, with a standard block type html element (like div, span, p, a...). However what I did (and works) is to use a selector, even amp-selector and simply use the event.targetOption to get the value of the result being clicked...

Its not exactly what I wanted but it is functionally equivalent so it will do.

Based on your comments I understand that you are using some html element other than an input, as a list item and therefore can't access corresponding value using event. Although this is not directly possible, this functionality can be mimicked by using AMP.setState. I assume your amp-list template looks something like follows :

<template type="amp-mustache">
    <span class="list-item">{{list-option}}</span>
</template>

You can try embedding the option value in the setState() for each list item using amp-mustache inside the template as follows :

<template type="amp-mustache">
  <span class="list-item" on="tap:AMP.setState({searchQuery : {{list-option}} })" >{{list-option}}</span>
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM