Reputation: 81
I have constructor of ViewModel below:
export class ViewModel{
data_1 = {id: 1, name: 'John'};
currency = {id: 1, name: 'USA'};
}
And in my html, I bind data by "with.bind":
<div with.bind="data_1">
<span textcontent.one-time="id"></span>
<span textcontent.one-time="name"></span>
<div with.bind="currency">
<span text.content="name"></span>
</div>
</div>
I have problem when I want to bind my currency in data_1, it can't not recognize currency . How can I get currency?
Upvotes: 1
Views: 2268
Reputation: 11
Using $parent alongside with.bind now works as of [email protected]
For example, the following will add a view model reference (bar) to the parent rather than to foo
<element with.bind="foo">
<child-element view-model.ref="$parent.bar"></child-element>
</element>
Upvotes: 0
Reputation: 1106
Why not just simplify and get rid of with.bind?
<div>
<span textcontent.one-time="data_1.id"></span>
<span textcontent.one-time="data_1.name"></span>
<div>
<span textcontent.one-time="currency.name"></span>
</div>
</div>
Upvotes: 4
Reputation: 193261
The thing is that with
attribute doesn't provide a reference to $parent
context. I'm not sure this is the best way to handle it but you can create your own custom attribute that would have $parent
.
Based on the original with
:
import {inject} from 'aurelia-dependency-injection';
import {BoundViewFactory, ViewSlot, customAttribute, bindable, templateController} from 'aurelia-templating';
@customAttribute('with-parent')
@templateController
@inject(BoundViewFactory, ViewSlot)
export class WithParent {
constructor(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
}
bind(executionContext) {
this.executionContext = executionContext;
this.valueChanged(this.value);
}
valueChanged(newValue) {
if (!this.view) {
newValue.$parent = this.executionContext;
this.view = this.viewFactory.create(newValue);
this.viewSlot.add(this.view);
}
else {
this.view.bind(newValue);
}
}
}
and then usage is transparent:
<div with-parent.bind="data_1">
<span textcontent.one-time="id"></span>
<span textcontent.one-time="name"></span>
<div with-parent.bind="$parent.currency">
<span textcontent.one-time="name"></span>
<div with-parent.bind="$parent.$parent.another">
<span textcontent.one-time="name"></span>
</div>
</div>
</div>
Upvotes: 0
Reputation: 878
$parent gives you a reference to your view model so $parent.currency
Upvotes: -1