greggreg
greggreg

Reputation: 12085

knockoutjs: binding to an observable property outside of an array, in a template

I'm trying to bind part of a template to a property that is on the root of my data model, while building the template off an observable array.

This jsfiddle: http://jsfiddle.net/mgxyE/2/ illustrates compactly what I'm trying to accomplish.

the span <span data-bind='text: message'></span> is what is failing because I can't figure out how to set up that binding inside a template. Any help?

Upvotes: 0

Views: 1852

Answers (2)

RP Niemeyer
RP Niemeyer

Reputation: 114792

If your viewmodel has global scope, then you can simply do:

<span data-bind='text: model.message'></span>

In your fiddle, you would want to change the option from onLoad to no wrap (body) for how the JavaScript is loaded.

Another options is to pass the value in via templateOptions. This would look like:

<div data-bind='template: {name :"nodeTemplate", foreach: nodes, templateOptions: { myMessage: message} }'></div>

Then, bind to it like (you could call it message, just used myMessage to show where the name comes from):

<span data-bind='text: $item.myMessage'></span>

Finally, if you use KO 1.3 beta, which I would recommend, then you can simply do:

<span data-bind='text: $root.message'></span>

Upvotes: 3

Tuan
Tuan

Reputation: 5412

With Knockout JS 1.3, you can use the parent binding context:

http://jsfiddle.net/Afx6d/

Upvotes: 1

Related Questions