-1

I'm working on a simple web page using knockout. Consider I have the following ViewModel function

self.sample_data = ko.observableArray([
  {
  1:[
        { title1:"abc", title2:"def"},
        { title1:"abc", title2:"def"}
    ],
  2:[
        { title1:"ghi", title2:"jkl"},
    ]
   }
]);

Am able to bind the specific json value with key value as '1' to the view layer as follows.

<h1 data-bind="text:sample_data[0].1[0].title1"></h1>

Consider I have two buttons 'previous' and 'next'. On clicking the button 'next' I should bind the data associated with key value as '2' in the JSON to the same h1 tag. How can we acheive that?

Amar Zeno
  • 412
  • 1
  • 6
  • 23
  • 1
    Just a nit to pick... there's no JSON in this question. You have a JavaScript literal, not JSON. JSON is a string representation of an object. – Jacob May 18 '14 at 18:27

2 Answers2

1

Your Json object has invalid key:

JSON only allows key names to be strings

Here's the binding sample

Html

<h1 data-bind="text: sample_data()[0][2][0].title1"></h1>

JavaScript

var self = {};
self.sample_data = ko.observableArray([
  {
  "1":[
        { title1:"abc11", title2:"def11"},
        { title1:"abc12", title2:"def12"}
    ],
  "2":[
        { title1:"ghi21", title2:"jkl21"},
    ]
   }]);  

ko.applyBindings(self);

You can play with code here

Community
  • 1
  • 1
GSerjo
  • 4,725
  • 1
  • 36
  • 55
1

You'll want an observable index variable in your view model. Clicking the next button would increment that variable:

var self = {};
self.sample_data = ko.observableArray([
    {
        "1": [
            { title1: "abc11", title2: "def11" },
            { title1: "abc12", title2: "def12" }
        ],
        "2": [
            { title1: "ghi21", title2: "jkl21" }
        ]
    }
]);
self.index = ko.observable(1);
self.goToNext = function() {
    self.index(self.index() + 1);
};

Then, your data binding could look something like this:

<h1 data-bind="text: sample_data()[0][index()][0].title1"></h1>
<a data-bind="click: goToNext">Next</a>
Jacob
  • 77,566
  • 24
  • 149
  • 228
  • 1
    `h1` binding is invalid, `sample_data` is an observable and observable it's a function, so you've to call it before access to any property. Don't forget about `ko.applyBindings(self);` Here's your [sample](http://jsfiddle.net/s3r8y/1/) – GSerjo May 18 '14 at 18:46