Question

I am trying to compute third field in view model.I know this is not the way but just giving the following snippet for example . Please Help

$.ajax({
    type: "GET",
    url: '/ASPNET/GetGroups',
    dataType: "json",
    success: function (data) {
        var viewModel = {
            advisorGroup: ko.observableArray(data)
        };
        viewModel.advisorGroup.label = ko.computed(function () {
            return self.code + ' (' + self.cls+')';
        });
        alert(JSON.stringify(viewModel));
        ko.applyBindings(viewModel);
    }
})


<input type="checkbox" data-bind="attr: { value: code, id: code }" name="GroupsSel" checked="checked">
<label data-bind="attr: { for: code }, text: label "></label>
Was it helpful?

Solution

Try this.

success: function (data) {
    ko.utils.arrayForEach(data, function(item){
        item.label = ko.computed(function () {
            return item.code + ' (' + item.cls + ')';
        });
    });
    //..........
}

Fiddle: http://jsfiddle.net/8WqQu/1/

Or as Anders noted, you could simply do this.

success: function (data) {
    ko.utils.arrayForEach(data, function(item){
        item.label = item.code + ' (' + item.cls + ')';
    });
    //..........
}

Fiddle: http://jsfiddle.net/8WqQu/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top