0

I have this observable array in my view model.

this.months = ko.observableArray(['Jan', 'Feb', 'Mar',...]); 

If I try to display each month, like this -

<!-- ko foreach: { data: months, as: 'month' } -->
<span data-bind="text: month"></span>        
<!-- /ko -->

It throws an error -

Uncaught ReferenceError: Unable to process binding "text: function (){return month }"
Message: month is not defined

If I try this,

<!-- ko foreach: months -->
<span data-bind="text: $data"></span>
<!-- /ko -->

it displays [object object]

What am I doing wrong?

Thanks.

2 Answers 2

2

I don't know what you're doing wrong, but this works fine. Looks like your months isn't what you think it is.

vm = {};

vm.months = ko.observableArray(['Jan', 'Feb', 'Mar']);

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!-- ko foreach: {data: months, as: 'month'} -->
<span data-bind="text: month"></span>
<!-- /ko -->

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

2 Comments

Not sure what I did wrong. I deleted everything knockout related from the page and added back one by one. And it works now.
I hate it when that happens.
0
`<span data-bind="text: month"></span>`

expects you to provide data with property month. but yours is array of string, therefore it will throw error. knockout is looking for month observable in that array.

As Roy suggested, below should work.

<!-- ko foreach: {data: months, as: 'month'} -->
<span data-bind="text: $data"></span>
<!-- /ko -->

Or you can change your observable array to provide observable data with month as property.

months = [{month:'jan'}, {month:'Feb'}, {month:'Mar'},...]);

make sure you provide observable array.

1 Comment

The as: 'month' allows you to use month instead of $data. I updated my example to illustrate.

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.