Skip to content

Instantly share code, notes, and snippets.

@pixels4nickels
Forked from Vheissu/app.html
Last active June 21, 2016 02:11
Show Gist options
  • Save pixels4nickels/4d07a8530f81951fb501a240727baf74 to your computer and use it in GitHub Desktop.
Save pixels4nickels/4d07a8530f81951fb501a240727baf74 to your computer and use it in GitHub Desktop.
Dynamic html template insertion with manual model binding
<template>
<require from='./my-element.html'></require>
</template>
import {inject} from 'aurelia-framework';
import {ViewFactory} from 'view-factory';
@inject(Element, ViewFactory)
export class App {
viewModel = { message: 'hello world' };
constructor(element, viewFactory) {
this.viewFactory = viewFactory;
this.element = element;
}
attached() {
this.viewFactory.insert(this.element, 'my-element', this.viewModel);
}
}
<!doctype html>
<html>
<head>
<title>Aurelia</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body aurelia-app="main">
<h1>Loading...</h1>
<script src="https://cdn.rawgit.com/jdanyow/aurelia-bundle/v1.0.3/jspm_packages/system.js"></script>
<script src="https://cdn.rawgit.com/jdanyow/aurelia-bundle/v1.0.3/config.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
<script>
System.import('aurelia-bootstrapper');
</script>
</body>
</html>
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
aurelia.start().then(a => a.setRoot());
}
<template>
<div>My Element</div>
</template>
textarea {
display: block;
}
import {
inject,
ViewCompiler,
Container,
ViewSlot,
createOverrideContext
} from 'aurelia-framework';
import {Loader} from 'aurelia-loader';
@inject(ViewCompiler, Container, Loader)
export class ViewFactory {
constructor(viewCompiler, container, loader) {
this.viewCompiler = viewCompiler;
this.loader = loader;
this.container = container;
}
insert(containerElement, htmlUrl, viewModel) {
try{
var viewFactory = _.find(this.loader.templateRegistry, function(entry){
return entry.address.indexOf(htmlUrl) !== -1;
}).factory;
}catch(error){
console.error('Could not find template registry entry containing "%s"', htmlUrl);
return;
}
let view = viewFactory.create(this.container);
let anchorIsContainer = true;
let viewSlot = new ViewSlot(containerElement, anchorIsContainer);
viewSlot.add(view);
view.bind(viewModel, createOverrideContext(viewModel));
return () => {
viewSlot.remove(view);
view.unbind();
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment