AngularJS nghref



  • Angular markup example {{name}} in an href will make the link go to the wrong URL if the user clicks it before loading.
  • <a href="http://www.wikitechy.com/profile/{{name}}">NAME</a>

  • In Angularjs we have a chance to replace the {{name}} markup with its value. Until Angular changes the markup the link will be broken and will return a 404 error. The ngHref directive will solves this problem.
  • <a ng-href="http://www.wikitechy.com/profile/{{name}}">NAME</a>

  • In AngularJS, the ng-href directive overrides the original href attribute of an <a> element.
  • If our application has AngularJS code inside the href value, the ng-href directive should be used instead of href.
  • The ng-href directive makes sure the link is not broken even if the user clicks the link before AngularJS has assessed the code.
  • The ng-href directive is compiling at the priority level “99”.

Syntax for ng-href directive in AngularJS:

<a ng-href= “string”></a>

Parameter value for ng-href directive in AngularJS:

Value Description
string It is a string value, or an expression resulting in a string.

Sample coding for ng-href directive in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorials</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
                    angular.min.js">
        </script>
    </head>
    <body ng-app="">
        <h2>ng-href Directive in AngularJS Tutorials</h2>
        <div ng- init="source=’http://www.Wikitechy.com’">
            <h3>Visit <a ng-href=” {{source}}”> {{ source}} </a>
                to learn new technology.</h3>
        </div>
    </body>
</html>

Code Explanation for ng-href directive in AngularJS:

Code Explanation for AngularJS nghref

  1. AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
  2. The AngularJS application is defined by ng-app=" ". The application runs inside the <body> tag. It’s also used to define a <body> tag as a root element.
  3. The ng-init=”source= ‘http://www.Wikitechy.com’ “ is used to define the initial value of the source variable is “http://www.Wikitechy.com”.
  4. The ng-href= “{{source}}” is used to dynamically bind source variable to the href attribute.
  5. The {{ source }} is used to dynamically bind the source value.

Sample Output for ng-href directive in AngularJS:

    Sample Output1 for AngularJS nghref

  1. The output shows that the user trying to open the http://www.Wikitechy.com href link.
  2. Sample Output2 for AngularJS nghref

  3. The output shows that the www.wikitechy.com page was loaded when the user click the ng-href attribute. In AngularJS, the ng-href attribute is safer than original href attribute.


Related Searches to angularjs ng-href directive