LazioTibijczyk
LazioTibijczyk

Reputation: 1937

Do not add hash to the URL after $location.hash

Some of my form pages are pretty tall. I've written a function to scroll to the first error on the form after hitting Save button like this

vm.scrollToError = function() {
    var anchor;

    for (var prop in vm.InwardLeaseForm.$error) {
        anchor = vm.InwardLeaseForm.$error[prop][0].$name;
        break;
    }

    $location.hash(anchor);
    $anchorScroll.yOffset = 300;
    $anchorScroll(anchor);
};

My problem is, this adds a hash with an id of the field to the URL. Is there a way to do this but not add this extra #vm.InwardLeaseForm_integerField_contractTerm_2 in this case to the URL?

Upvotes: 0

Views: 90

Answers (1)

C3roe
C3roe

Reputation: 96316

My problem is, this adds a hash with an id of the field to the URL.

Well, that’s what $location.hash(anchor); does. So remove it, if you don’t want it to happen …

I thought this is necessary for the $anchorScroll to work.

Reading documentation helps ;-) - https://docs.angularjs.org/api/ng/service/$anchorScroll:

When called, it scrolls to the element related to the specified hash or (if omitted) to the current value of $location.hash()

So, this only falls back onto the current location hash value, if you don’t explicitly specify what element to scroll to - but since you are using $anchorScroll(anchor);, modifying the location hash prior to this isn’t even necessary here.

Upvotes: 1

Related Questions