40
votes

I'm trying to bind anchor attributes to a KnockoutJS ViewModel field. I tried something like this:

<a data-bind="href: Link, value: Title"></a>

but this doesn't work. Where I can get a list of possible data-bind values for html elements?

4

4 Answers

97
votes

You need to use the attr binding, this allows you to set any attribute you like.

For example:

<a data-bind="attr: { href: Link, title: Title }, text: Title">xxx</a>
12
votes

Here you can find a list of all possible bindings.

http://knockoutjs.com/documentation/value-binding.html

on the left side (sidebar) you find links to other bindings like text, attr style and more.

You can do this

attr: { href: Link}, text: Title like xwrscommented

or create a template http://knockoutjs.com/documentation/template-binding.html

hope this helps

1
votes

As an alternative to @RichardFriend's answer (and more commonly used option), you could write a custom binding handler to make your views a wee bit more terse:

ko.bindingHandlers['href'] = {
  update: function(element, valueAccessor) {
    element.href = ko.utils.unwrapObservable(valueAccessor());
  }
};

ko.applyBindings({
  myUrl: 'http://stackoverflow.com',
  myText: 'Stack Overflow website'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<a data-bind="href: myUrl, text: myText"></a>
0
votes

This works perfect for me

            <td class="CommandArea" rowspan="2">
            <p><a href='#' data-bind="click: abandon" >Abandon</a></p>
            </td>