How to call a function in AngularJs when route matches?

Upvote picture Upvote · May 5, 2013 · Viewed 25.4k times · Source
$routeProvider.when('/ticket', {
    controller: TicketController, 
    templateUrl: Routing.generate('ticket_list')
});

displays a simple list where each entry is selectable. However on select no extra view is loaded. Every thing is in ticket_lost template. The template has some hidden fields that are revealed when entry is clicked.

I can define which entry is selected internally by setting

selectedTicket = 1;

So when there is a route like

/ticket/1

I want to call a function that sets selectedTicket to 1. Is that possible? How to do that? What do I have to change in routing?

Answer

Dmitry Evseev picture Dmitry Evseev · May 5, 2013

Take a look at $routeParams service. It allows to set up route with parameters which will be parsed by service:

// Given:
// URL: http://server.com/index.html#/ticket/1
// Route: /ticket/:ticketId
//
// Then
$routeParams ==> {ticketId:1}

In your controller:

angular.module('myApp')
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/ticket', {controller: 'TicketController'});
        $routeProvider.when('/ticket/:ticketId', {controller: 'TicketController'});
        $routeProvider.otherwise({redirectTo: '/ticket'});
    }])
    .controller('TicketController', function ($scope, $routeParams) {
        var init = function () {
            if ($routeParams.ticketId) {
                $scope.ticketSelected($routeParams.ticketId);
            }
        };

        // fire on controller loaded
        init();
    });