Angular: prevent default behaviour of the a-tag

When working with buttons or links in web projects you maybe use a # as the href value as shown below.

<a id="make-button" href="#" ng-click="make()">

If we wanted to listen for its click events we’d use the ng-click attribute and assign it a function name.

The following controller code basically shows the definition of the make function which would be executed whenever a user clicks on the previously defined link.

  .controller('MainCtrl', function ($scope) {
    $scope.make = function() {
      return false;

There’s nothing wrong with this controller but you’ll notice that your browser is reloading the page when clicking on the link. If there was no output in the make function your conclusion could be that the function isn’t called at all since return false would prevent the browser’s default behaviour.

Unfortunately you’d be on the wrong track. The reason why the page is reloaded is because of the hash. Simply leave the value blank or completely remove the href attribute. You’ll be fine then.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>