Knockout Js - Binding a single item from a json array to an element

10,274

Suggested solution:

   function ReservationsViewModel() {
        var self = this;


        self.availableMeals = ko.observableArray([
            { mealName: "Standard (sandwich)", price: 0, id = 1 },
            { mealName: "Premium (lobster)", price: 34.95, id = 2 },
            { mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
        ]);

        self.getMealById = function(id) {
            ko.utils.filterArray(self.availableMeals(), function(item) {
                return item.id == id;
            });
        };
  }

In the view:

<input type="text" id="firstElementMealName" data-bind="value: getMealById(1)"></input>

EDIT: here is a two-way solution:

function ReservationsViewModel() {
        var self = this;


    self.availableMeals = ko.observable({            
        id_1: { mealName: "Standard (sandwich)", price: ko.observable(0) },
        id_2: { mealName: "Premium (lobster)", price: ko.observable(34.95) },
        id_3: { mealName: "Ultimate (whole zebra)", price: ko.observable(290) }
        });
  }

ko.applyBindings(new ReservationsViewModel());

In the View:

<input type="text" id="firstElementMealName" data-bind="value: availableMeals().id_2.price()"></input>
Share:
10,274

Related videos on Youtube

Faris Zacina
Author by

Faris Zacina

Build, Measure and Learn. Ministry of Programming Sarajevo JavaScript

Updated on June 04, 2022

Comments

  • Faris Zacina
    Faris Zacina almost 2 years

    I have the following view model which contains an array of elements

       function ReservationsViewModel() {
            var self = this;
    
    
            self.availableMeals = [
                { mealName: "Standard (sandwich)", price: 0, id = 1 },
                { mealName: "Premium (lobster)", price: 34.95, id = 2 },
                { mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
            ];  
      }
    

    I want to bind this view model to a input, but i want to bind only the Single array element meal name that has the id value as the data-id attribute of the input.

    <input type="text" id="firstElementMealName" data-id="1" data-bind="value: ??"></input>
    

    In this example i would bind the array element with id = 1, and the text would appear as "Standard (Sandwich)", but i still need the full binding and change tracking (observables) and all the other good stuff in Knockout.

    How to pick up the data-id and use it in the binding code to bind the appropriate meal to the input?

    Thanks in advance

  • Faris Zacina
    Faris Zacina over 12 years
    It works in one direction, but i still don't get the two-way binding. i would like the price to display in the input, and then when i change it i would like the binding to update it automatically in the viewmodel?
  • Gigi2m02
    Gigi2m02 over 10 years
    Looks like the getMealById function is missing a closing ')'?