dynamically change the path of href angular JS

17,289

Solution 1

Use different controllers for each page. You can use a variable for link and set it in the related controller. For example:

<a href="#/{{myLink}}">Demo</a>

or

<a ng-href="#/{{myLink}}">Demo</a>

And in the each related controller:

$scope.myLink="page1";

or

$scope.myLink="page2";

etc.

Or if you insist to use same controller, you can check the location path:

if ($location.path().substring(1) == "page1") {
    $scope.myLink="page2";
}

Solution 2

Use ng-href instead - it will automatically update when the bound value changes.

Share:
17,289
user1853128
Author by

user1853128

Updated on August 29, 2022

Comments

  • user1853128
    user1853128 over 1 year

    I am trying to change the href value on click of it.

    This is what I have tried.

    HTML:

    <a href="#Page1">Demo</a>
    

    JS:

        angular.config(function ($routeProvider) {
            $routeProvider
        .when('/Page1', {
                templateUrl: 'main.html'
                controller: 'FirstController'
            })
     .when('/Page2', {
                templateUrl: 'sub.html'
                controller: 'FirstController'
            })
    .otherwise('main.html');
    

    How do I change the path of the anchor tag everytime when I clicked on it.

    Can anyone please help me out.

  • drew_w
    drew_w almost 10 years
    Its similar, but ng-href is a slightly better option!
  • Julix
    Julix over 7 years
    not that useful without explaining or linking to an explanation for why it's a better option... - nevermind, just found it in a comment above and the other solution below.