41

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?

0

4 Answers 4

99

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>
0
12

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
  • Thanks. Solution found <a data-bind="attr: { href: Link}, text: Title"> </a>
    – xwrs
    Commented Nov 14, 2011 at 14:45
1

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

This works perfect for me

            <td class="CommandArea" rowspan="2">
            <p><a href='#' data-bind="click: abandon" >Abandon</a></p>
            </td>
1
  • Can you edit your answer and explain how it answers the question? Commented May 8, 2018 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.