Durandal navigation: attr href binding not working

820 Views Asked by At

I have the following setup in Durandal for navigation:

layout.js

...
that.activate = function () {
    router.map([
        { route: '', title: abp.localization.localize('HomePage', 'MyProject'), moduleId: 'viewmodels/home', nav: true, menuName: 'Home' },
        { route: 'editpage/:id', title: abp.localization.localize('EditPage', 'MyProject'), moduleId: 'viewmodels/editpage', hash: '#/editpage/id' }
    ]).buildNavigationModel();

pages.js

...
that.editPage = function (page) {
    that.router.navigate('editpage/' + page.id());
};

pages.cshtml

<ul class="list-group" data-bind="foreach: pages">
    <div class="list-group-item">
        <span class="page-name" data-bind="text: name"></span>
        <div class="text-right">
            <!--<button type="button" class="btn btn-info btn-sm" data-bind="click: $parent.editPage">-->
            <button type="button" class="btn btn-info btn-sm" data-bind="attr: {href: '#/editpage/' + id()}">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> @L("EditPage")
            </button>
        </div>
    </div>
</ul>

I'd like to navigate to the "EditPage/:id" page when I hit the Edit Page button. However only the click binding works:

<button type="button" class="btn btn-info btn-sm" data-bind="click: $parent.editPage">

The attr href binding does not:

<button type="button" class="btn btn-info btn-sm" data-bind="attr: {href: '#/editpage/' + id()}">

I tried several ways of configuration but none of them seemed to help. I guess its just an improper syntax in the route configuration or in the hash. Couldn't figure it out.

Any help would be appreciated!

2

There are 2 best solutions below

1
On BEST ANSWER

Try this

<a class="btn btn-info btn-sm" data-bind="attr: { href: '#editpage/' + id() }"></a>

1) Use href attr with a tag instead of button
2) Removed unnecessary / after #

   #/editpage/ changed to #editpage/
1
On

I haven't used the hash parameter before. However, according to the router documentation (http://durandaljs.com/documentation/Using-The-Router.html), the hash you're looking for here is literally #/editpage/id and the hash you're passing is '#/editpage/' + id(). Try writing the following instead:

Router:

{ route: 'editpage/:id', title: abp.localization.localize('EditPage', 'MyProject'), moduleId: 'viewmodels/editpage', hash: '#editpage/:id' }

Page

<button type="button" class="btn btn-info btn-sm" data-bind="attr: {href: '#editpage/' + id()}">

Additionally, if you simply hyperlink to the route (as you have done) and remove the hash parameter from the route, you should be fine.