TheGr8_Nik
TheGr8_Nik

Reputation: 3200

Aurelia dynamic load

Is there a possibility with Aurelia to load a view with his viewmodel dynamically? For example I have a list of modules, I click one of them and the target view will be loaded in the page. The list is not known a priori, so I can't load all modules.

model example.js

export class Modules{
  list = [];

  constructor(socket) {
    socket.on('update', list => this.list);
  }

  select(module) {
    //load and display the module view
  }
}

view example.html

<template>
  <ul>
    <li repeat.for="module of list" click.delegate="$parent.select(module)">${module.name}</li>
  </ul>
  <div class="target">
    <!-- Here should be loaded the module -->
  </div>
</template>

Upvotes: 2

Views: 2068

Answers (1)

Jeremy Danyow
Jeremy Danyow

Reputation: 26406

Approach 1

Load the data in your app.js class's configureRouter method. Once the data is loaded you can configure the router. Just be sure to return a promise from configureRouter.

Approach 2

Use Aurelia's <compose> element to compose the selected module with the appropriate view.

Here's a working plunk

And the code:

app.js

import {inject} from 'aurelia-framework';
import {MockSocket} from './mock-socket';

@inject(MockSocket)
export class App {
  list;
  selectedModule;
  
  constructor(socket) {
    socket.on('update', list => this.list = list);
  }

  select(module) {
    this.selectedModule = module;
  }
}

app.html

<template>
  <ul>
    <li repeat.for="module of list">
      <button type="button" click.delegate="$parent.select(module)">${module.path}</button>
    </li>
  </ul>
  <div class="target">
    <compose view-model.bind="selectedModule.path"></compose>
  </div>
</template>

Upvotes: 4

Related Questions