简体   繁体   中英

How to dynamically change the template in aurelia / click to edit table row?

With knockout I could dynamically change the template of a table row so that when I clicked on it, the row would become editable using an edit template. No navigation, no routing, just assigning the row a new template. How do I do this in aurelia?

Here's how you could accomplish this using the if binding command:

https://gist.run/?id=2408b065ecfac30ff2b1034ea8da800d

截图


Code:

app.js

export class App {
  editing = null;

  planets = [
    { name: 'Mercury', diameter: 3032, distance: 35983610 },
    { name: 'Venus', diameter: 7521, distance: 67232360 },
    { name: 'Earth', diameter: 7926, distance: 92957100 },
    { name: 'Mars', diameter: 4222, distance: 141635300 },
    { name: 'Jupiter', diameter: 88846, distance: 483632000 },
    { name: 'Saturn', diameter: 74898, distance: 888188000 },
    { name: 'Uranus', diameter: 31763, distance: 1783950000 },
    { name: 'Neptune', diameter: 30778, distance: 2798842000 }];

  edit(planet) {
    this.editing = planet;
  }
}

app.html

<template>
  <table>
    <thead>
      <tr>
        <td>Planet</td>
        <td>Diameter (mi)</td>
        <td>Distance to Sun (mi)</td>
      </tr>
    </thead>
    <tbody>
      <tr repeat.for="planet of planets" click.delegate="edit(planet)">
        <!-- read-only mode -->
        <td if.bind="editing !== planet">${planet.name}</td>
        <td if.bind="editing !== planet">${planet.diameter}</td>
        <td if.bind="editing !== planet">${planet.distance}</td>

        <!-- edit-mode -->
        <td if.bind="editing === planet"><input value.bind="planet.name" type="text"></td>
        <td if.bind="editing === planet"><input value.bind="planet.diameter" type="number"></td>
        <td if.bind="editing === planet"><input value.bind="planet.distance" type="number"></td>
      </tr>
    </tbody>
  </table>
</template>

css:

thead {
  font-weight: bold;
}

tbody > tr > td {
  cursor: pointer;
}

you can use a view strategy to dynamically choose the view for the view model.

http://aurelia.io/docs.html#compose - scroll down to the part about view strategy

What if you want to determine the view dynamically based on data though? or runtime conditions? You can do that too by implementing a getViewStrategy() method on your view-model. It can return a relative path to the view or an instance of a ViewStrategy for custom view loading behavior. The nice part is that this method is executed after the activate callback, so you have access to the model data when determining the view.

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