a – Anchor Tag Directive


a – Anchor Tag Directive: This directive modifies the default behaviour of the anchor tag in AngularJs. If you leave href attribute value null then default action will be prevented. Here in this tutorial we are going to explain how you can use anchor tags in AngularJs. You can use our online editor to edit and run the code online.


a – Anchor Tag Directive | Anchor Tag in AngularJs | Example

Sytax for a is as below-

Syntax –

angular.merge Syntax

<a>...</a>

AngularJs Modifiy the default behaviour of the anchor(..). If the value of href attribute is blank it will prevent the default action. So if you want to call a function using ng-click and prevent the href action just leave the href attribute null.

Now let us create a simple example to understand the default and the AngularJs anchor tage behaviour .

Example

a – Anchor Tag Directive

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
  $scope.result = '';
  $scope.testFn = function() {
	  $scope.result = 'You Clicked Me!';  
  }
});
function myFn(){
	alert("Called From Outside");	
}
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController"> 
    <h3>Inside AngularJs App</h3> 
    <a href="" ng-click ="testFn()" >Test Function</a>
	<br>
	Result = {{result}}
</div> 
</div>

    <h3>Outside AngularJs App</h3> 
	<a href="" onclick ="myFn()" >My Function</a>

</body>  
</html>                                                                                                                                                                           

Try it »

If you click on the above two anchors you will clearly see the difference in the href Action. Angular will stop action while in second example it will call the function and redirect to same url.

If you run the above example it will produce the output something like this –

a – Anchor Tag Directive


Advertisements

Add Comment