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.
- 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.
- 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”.
<a href="http://www.wikitechy.com/profile/{{name}}">NAME</a>
<a ng-href="http://www.wikitechy.com/profile/{{name}}">NAME</a>
Syntax for ng-href directive in AngularJS:
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:
Code Explanation for ng-href directive in AngularJS:
- AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
- 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.
- The ng-init=”source= ‘http://www.Wikitechy.com’ “ is used to define the initial value of the source variable is “http://www.Wikitechy.com”.
- The ng-href= “{{source}}” is used to dynamically bind source variable to the href attribute.
- The {{ source }} is used to dynamically bind the source value.
Sample Output for ng-href directive in AngularJS:
- The output shows that the user trying to open the http://www.Wikitechy.com href link.
- 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.