0

I have this fiddle. All I want to do is , convert the values nested in each object literal to a string.

<ul data-bind="foreach: people">
    <li>
       <span data-bind="text: Name"> </span>

        <span data-bind="text:Id"></span>

    </li>
</ul>



 function AppViewModel()
{
    var self = this;
    self.people = ko.observableArray([{"Name":"RobbStark",Id:1}, {"Name":"JohnSnow",Id:2}]);
}

ko.applyBindings(new AppViewModel());

I want to use a lookup like

var valueMap={
    1:"SanJose",
    2:"San Francisco"
}

To get output like

RobbStark SanJose
JohnSnow San Francisco.

How do I convert the observable to a different value inside foreach ?

1 Answer 1

2

All you have to do is call a javascript function from your text data-binding, passing in the current item ($data) from the for each loop as a parameter. Example fiddle

Javascript:

var valueMap={
    1:"SanJose",
    2:"San Francisco"
}

 function AppViewModel()
{
    var self = this;

    self.people = ko.observableArray([{"Name":"RobbStark",Id:1}, {"Name":"JohnSnow",Id:2}]);
    self.parsedName = function (item) {
        return item.Name + " " + valueMap[item.Id];
    };
}

ko.applyBindings(new AppViewModel());

HTML

<ul data-bind="foreach: people">
    <li>
       <span data-bind="text: $root.parsedName($data)"> </span>
    </li>
</ul>

Note #1 under the KnockoutJS documentation contains more information about $data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.