2

I've got a list of universities that I have generated from a json file, and I want to add a hyperlink for each university in the list generated so that I can navigate to each of their respective university pages.

HTML

<ul data-bind="foreach: university">
   <li data-bind="text: university"></li>
</ul>

I have been using knockout.js to get the json data to appear in the html and I was wondering whether there was a way to do this without hardcoding each link into the html?

JSON file

{
"universities": [
    {
        "university": "Cambridge"
    },
    {
        "university": "Oxford"
    },
    {
        "university": "UEA"
    }
]
}

Thanks for any help :)

  • Take a look at the [`attr` binding](http://knockoutjs.com/documentation/attr-binding.html). – Shawn Bush Apr 29 '14 at 18:16
  • possible duplicate http://stackoverflow.com/questions/16364460/knockout-html-href – Smeegs Apr 29 '14 at 18:17
  • Where do you want your anchor to point to? "~/Universities/Cambridge" ? Anchor href has to be generated based on some piece of data. data-bind="attr: {href:'link'}" – milagvoniduak Apr 29 '14 at 18:17
  • "services/profile.jsp?uni=Cambridge" would be where the link would go. Would I add: "href: "services/profile.jsp?uni=Cambridge" to the json file and then call it how you've mentioned in the html? @MyP3uK –  Apr 29 '14 at 18:29

1 Answers1

2

your HTML should look like

FIDDLE

<ul data-bind="foreach: universities">
    <li> <a data-bind="text: university, attr: { href: 'services/profile.jsp?uni=' + university }"></a> </li>
</ul>
milagvoniduak
  • 3,214
  • 1
  • 18
  • 18