0

Is it possible to declare a javascript function in your knockout foreach binding? I want to generate a list from a javascript function outside of my view model.

 <select class="form-control" data-bind="foreach: { data: function() { // return list values } }">
 <option data-bind="text: Value, attr: { value: Value }"></option>
            </select>
3
  • why do u want to do this? what are you trying to achieve? Commented Oct 28, 2013 at 16:48
  • I'm trying to pull from a globally defined javascript list. Commented Oct 28, 2013 at 16:51
  • 1
    You should call that global list from your VM, its there for that reason Commented Oct 28, 2013 at 17:20

1 Answer 1

1

No quite sure what you are trying to achieve with <option data-bind="text: Value, attr: { value: Value }"></option>.

Have a look at my fiddle for a few different setups. It contains usages of both options and foreach bindings on a select element.

To answer the question, you provide a function in your viewModel to provide the desired data. As long as your viewModel can "access" the data, the function will provide it to the binding. If the data were to be a simple list of literals, then all that is required :

Javascript:

var listOfLiterals = function() { return  ["One", "Two", "Three"] };

  var viewModel = {
     selectedLiteral: ko.observable(),  
     getLiterals: function() {
       return listOfLiterals();
  }
}

HTML:

<select data-bind="options: getLiterals(), value: selectedLiteral"></select>
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.