How/when to use ng-click to call a route?

Robert Christian picture Robert Christian · Jan 7, 2013 · Viewed 360k times · Source

Suppose you are using routes:

// bootstrap
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

    $routeProvider.when('/home', {
        templateUrl: 'partials/home.html',
        controller: 'HomeCtrl'
    });
    $routeProvider.when('/about', {
        templateUrl: 'partials/about.html',
        controller: 'AboutCtrl'
    });
...

And in your html, you want to navigate to the about page when a button is clicked. One way would be

<a href="#/about">

... but it seems ng-click would be useful here too.

  1. Is that assumption correct? That ng-click be used instead of anchor?
  2. If so, how would that work? IE:

<div ng-click="/about">

Answer

Josh David Miller picture Josh David Miller · Jan 7, 2013

Routes monitor the $location service and respond to changes in URL (typically through the hash). To "activate" a route, you simply change the URL. The easiest way to do that is with anchor tags.

<a href="#/home">Go Home</a>
<a href="#/about">Go to About</a>

Nothing more complicated is needed. If, however, you must do this from code, the proper way is by using the $location service:

$scope.go = function ( path ) {
  $location.path( path );
};

Which, for example, a button could trigger:

<button ng-click="go('/home')"></button>