Skip to content
Related Articles

Related Articles

AngularJS ng-href Directive

Improve Article
Save Article
  • Last Updated : 24 Aug, 2022
Improve Article
Save Article

The ng-href directive is used when we have an angular expression inside the href value. If href attribute is used then the problem is that if in case the link is clicked before AngularJS has replaced the expression with its value then it may go to the wrong URL and the link will be broken and will most likely return a 404 error while ng-href directive checks that the link is not broken even if the link is clicked before the code evaluation by AngularJS. 

Syntax:

<element ng-href="addr">
     Content ... 
</element> 

Parameter value:

  • addr: It refers to the string containing the angular expression.

Example 1: This example describes the use of the ng-href Directive in AngularJS, where the ng-init directive is used to initialize AngularJS Application data, & contains the URL.

HTML




<!DOCTYPE html>
<html>
  
<head>
      <title>
        AngularJS ng-href Directive
    </title>
    <script src=
    </script>
    <style>
        body {
            text-align: center;
            font-family: Arial, Helvetica, sans-serif;
        }
    </style>
</head>
  
<body ng-app="" style="text-align:center">
    <div ng-init="url = 'https://www.geeksforgeeks.org/'">
        <h1 style="color:green">GeeksforGeeks</h1>
        <h2>ng-href Directive</h2>
        <p>Go to 
            <a ng-href="{{url}}">GeeksforGeeks</a>
        </p>
    </div>
</body>
</html>

Output:

 

Example 2: This is another example that describes the ng-href Directive in AngularJS.

HTML




<!DOCTYPE html>
<html ng-app="">
  
<head>
    <title>
        AngularJS ng-href Directive
    </title>
    <script src=
    </script>
    <style>
        body {
            text-align: center;
            font-family: Arial, Helvetica, sans-serif;
        }
  
        h1 {
            color: green;
        }
    </style>
</head>
  
<body ng-controller="gfg">
    <h1>GeeksforGeeks</h1>
    <h3>ng-href Directive</h3>
    <a ng-href="{{ webpage }}">
        GeeksforGeeks
    </a>
  
    <script>
        function gfg($scope) {
            $scope.webpage = 
                  "https://www.geeksforgeeks.org/";
        }
    </script>
</body>
</html>

Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!