
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
AngularJS ngHref Directive
The ngHref Directive in AngularJS solves the problem of replacing the markup when the link is broken which thus leads the system to return a 404 error. Instead of using markup like {{hash}} in an href attribute which will change or replace the markup value, we should use the ngHref directive since that link can be broken and thus leads to return a System Error.
Syntax
<element ng-href="expression">..content..</element>
Example − ngHref Directive
Create a file "ngHref.html" in your Angular project directory and copy-paste the following code snippet.
<!DOCTYPE html> <html> <head> <title>ngHref Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body ng-app="" style="text-align: center;"> <h1 style="color: green;"> Welcome to Tutorials Point </h1> <h2> AngularJS | ngHref Directive </h2> <div ng-init="url ='https://www.tutorialspoint.com/index.htm'"> <p>Go to <a ng-href="{{url}}">TutorialsPoint</a></p> </div> </body> </html>
Output
To run the above code, just go to your file and run it as a normal HTML file.
Example 2
Create a file "ngHref.html" in your Angular project directory and copy-paste the following code snippet.
<!DOCTYPE html> <html> <head> <title>ngHref Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body ng-app="" style="text-align: center;"> <h1 style="color: green;"> Welcome to Tutorials Point </h1> <h2> AngularJS | ngHref Directive </h2> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, This link will not reload)<br/> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link,This link will not reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, Thislink will reload!)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (nolink)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </body> </html>
Output
To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window.