Data-bind href attribute for anchor tag

58,020

Solution 1

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>

Solution 2

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

Solution 3

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>
Share:
58,020
xwrs
Author by

xwrs

Updated on July 09, 2022

Comments

  • xwrs
    xwrs almost 2 years

    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?

  • xwrs
    xwrs over 12 years
    Thanks. Solution found <a data-bind="attr: { href: Link}, text: Title"> </a>
  • soundslikeodd
    soundslikeodd almost 6 years
    Can you edit your answer and explain how it answers the question?