0
votes

I am learning Aurelia.

My question:

I have a hard-coded view that looks like this:

app.html

<template> 
    <div>
        <label for="firstname">First Name</label>
        <input type="text" name="firstname" value="Bob">
        <label for="firstname">Last Name</label>
        <input type="text" name="lastname" value="Tanner">
   </div>

   <div>
       <label for="firstname">First Name</label>
       <input type="text" name="firstname" value="Lynda">
       <label for="firstname">Last Name</label>
       <input type="text" name="lastname" value="Kay">
   </div>

    <div>
        <label for="firstname">First Name</label>
        <input type="text" name="firstname" value="Alan">
        <label for="firstname">Last Name</label>
        <input type="text" name="lastname" value="Jones">
   </div>

   <button click.trigger="addEntries()">add entries</button>
</template>

When the user clicks the button I want the result to be a data structure that looks like this:

this.entries = [
  {firstname:"Bob", lastname:"Tanner"},
  {firstname:"Lynda", lastname:"Kay"},
  {firstname:"Alan", lastname:"Jones"}
]

Here is the rest of my code

app.js

import {WorkEntry} from 'components/work_entry';

export class App {
  constructor() {
    this.firstname = "";
    this.lastname = "";
    this.entries = [];
  }

  addEntry(){
    this.entries.push(new WorkEntry(this.firstname,this.lastname))

  }

  addEntries(){
     // ??
     // loop through dom elements ?
  }
}

work_entry.js

export class WorkEntry {
    constructor(firstname,lastname){
        this.firstname = firstname;
        this.lastname = lastname;
    }
}
1
You have no bindings set up in order to see the values in the view model. aurelia.io/hub.html#/doc/article/aurelia/binding/latest/… - R. Richards
Why is your template hard coded? - Ashley Grant

1 Answers

1
votes

You want to loop through your entries array and bind the inputs to the properties of each item.

<template> 
    <div repeat.for="entry of entries">
        <label for="firstname">First Name</label>
        <input type="text" name="firstname" value.bind="entry.firstname">
        <label for="firstname">Last Name</label>
        <input type="text" name="lastname" value.bind="entry.lastname">
    </div>
</template>

If you want the view to begin with data already, just instantiate your this.entries array with that data and it will be displayed. If the user changes the value in the inputs, the corresponding item in the array will also be updated with that value.