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

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">

The answer is


Here's a great tip that nobody mentioned. In the controller that the function is within, you need to include the location provider:

app.controller('SlideController', ['$scope', '$location',function($scope, $location){ 
$scope.goNext = function (hash) { 
$location.path(hash);
 }

;]);

 <!--the code to call it from within the partial:---> <div ng-click='goNext("/page2")'>next page</div>

I used ng-click directive to call a function, while requesting route templateUrl, to decide which <div> has to be show or hide inside route templateUrl page or for different scenarios.

AngularJS 1.6.9

Lets see an example, when in routing page, I need either the add <div> or the edit <div>, which I control using the parent controller models $scope.addProduct and $scope.editProduct boolean.

RoutingTesting.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <title>Testing</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.min.js"></script>_x000D_
    <script>_x000D_
        var app = angular.module("MyApp", ["ngRoute"]);_x000D_
_x000D_
        app.config(function($routeProvider){_x000D_
            $routeProvider_x000D_
                .when("/TestingPage", {_x000D_
                    templateUrl: "TestingPage.html"_x000D_
                });_x000D_
        });_x000D_
_x000D_
        app.controller("HomeController", function($scope, $location){_x000D_
_x000D_
            $scope.init = function(){_x000D_
                $scope.addProduct = false;_x000D_
                $scope.editProduct = false;_x000D_
            }_x000D_
_x000D_
            $scope.productOperation = function(operationType, productId){_x000D_
                $scope.addProduct = false;_x000D_
                $scope.editProduct = false;_x000D_
_x000D_
                if(operationType === "add"){_x000D_
                    $scope.addProduct = true;_x000D_
                    console.log("Add productOperation requested...");_x000D_
                }else if(operationType === "edit"){_x000D_
                    $scope.editProduct = true;_x000D_
                    console.log("Edit productOperation requested : " + productId);_x000D_
                }_x000D_
_x000D_
                //*************** VERY IMPORTANT NOTE ***************_x000D_
                //comment this $location.path("..."); line, when using <a> anchor tags,_x000D_
                //only useful when <a> below given are commented, and using <input> controls_x000D_
                $location.path("TestingPage");_x000D_
            };_x000D_
_x000D_
        });_x000D_
    </script>_x000D_
</head>_x000D_
<body ng-app="MyApp" ng-controller="HomeController">_x000D_
_x000D_
    <div ng-init="init()">_x000D_
_x000D_
        <!-- Either use <a>anchor tag or input type=button -->_x000D_
_x000D_
        <!--<a href="#!TestingPage" ng-click="productOperation('add', -1)">Add Product</a>-->_x000D_
        <!--<br><br>-->_x000D_
        <!--<a href="#!TestingPage" ng-click="productOperation('edit', 10)">Edit Product</a>-->_x000D_
_x000D_
        <input type="button" ng-click="productOperation('add', -1)" value="Add Product"/>_x000D_
        <br><br>_x000D_
        <input type="button" ng-click="productOperation('edit', 10)" value="Edit Product"/>_x000D_
        <pre>addProduct : {{addProduct}}</pre>_x000D_
        <pre>editProduct : {{editProduct}}</pre>_x000D_
        <ng-view></ng-view>_x000D_
_x000D_
    </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

TestingPage.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <title>Title</title>_x000D_
    <style>_x000D_
        .productOperation{_x000D_
            position:fixed;_x000D_
            top: 50%;_x000D_
            left: 50%;_x000D_
            width:30em;_x000D_
            height:18em;_x000D_
            margin-left: -15em; /*set to a negative number 1/2 of your width*/_x000D_
            margin-top: -9em; /*set to a negative number 1/2 of your height*/_x000D_
            border: 1px solid #ccc;_x000D_
            background: yellow;_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="productOperation" >_x000D_
_x000D_
    <div ng-show="addProduct">_x000D_
        <h2 >Add Product enabled</h2>_x000D_
    </div>_x000D_
_x000D_
    <div ng-show="editProduct">_x000D_
        <h2>Edit Product enabled</h2>_x000D_
    </div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

both pages - RoutingTesting.html(parent), TestingPage.html(routing page) are in the same directory,

Hope this will help someone.


just do it as follows in your html write:

<button ng-click="going()">goto</button>

And in your controller, add $state as follows:

.controller('homeCTRL', function($scope, **$state**) {

$scope.going = function(){

$state.go('your route');

}

})

Another solution but without using ng-click which still works even for other tags than <a>:

<tr [routerLink]="['/about']">

This way you can also pass parameters to your route: https://stackoverflow.com/a/40045556/838494

(This is my first day with angular. Gentle feedback is welcome)


Remember that if you use ng-click for routing you will not be able to right-click the element and choose 'open in new tab' or ctrl clicking the link. I try to use ng-href when in comes to navigation. ng-click is better to use on buttons for operations or visual effects like collapse. But About I would not recommend. If you change the route you might need to change in a lot of placed in the application. Have a method returning the link. ex: About. This method you place in a utility


Using a custom attribute (implemented with a directive) is perhaps the cleanest way. Here's my version, based on @Josh and @sean's suggestions.

angular.module('mymodule', [])

// Click to navigate
// similar to <a href="#/partial"> but hash is not required, 
// e.g. <div click-link="/partial">
.directive('clickLink', ['$location', function($location) {
    return {
        link: function(scope, element, attrs) {
            element.on('click', function() {
                scope.$apply(function() {
                    $location.path(attrs.clickLink);
                });
            });
        }
    }
}]);

It has some useful features, but I'm new to Angular so there's probably room for improvement.


You can use:

<a ng-href="#/about">About</a>

If you want some dynamic variable inside href you can do like this way:

<a ng-href="{{link + 123}}">Link to 123</a>

Where link is Angular scope variable.


Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to routes

How to open a link in new tab using angular? How to Refresh a Component in Angular laravel Unable to prepare route ... for serialization. Uses Closure How to use router.navigateByUrl and router.navigate in Angular No provider for Router? Difference between [routerLink] and routerLink How to force Laravel Project to use HTTPS for all routes? Change route params without reloading in Angular 2 Angular 2 router no base href set How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

Examples related to angularjs-routing

What is the difference between $routeProvider and $stateProvider? Changing route doesn't scroll to top in the new page What is the difference between angular-route and angular-ui-router? Can angularjs routes have optional parameter values? Angular - ui-router get previous state angularjs getting previous route path How/when to use ng-click to call a route? Delaying AngularJS route change until model loaded to prevent flicker

Examples related to angularjs-ng-click

AngularJS : ng-click not working How to trigger ngClick programmatically Automatically pass $event with ng-click? adding and removing classes in angularJs using ng-click AngularJS ng-click stopPropagation Pass a reference to DOM object with ng-click Adding parameter to ng-click function inside ng-repeat doesn't seem to work How/when to use ng-click to call a route?

Examples related to angularjs-ng-route

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