Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function in AngularJs when route matches?

$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?

like image 234
UpCat Avatar asked May 05 '13 11:05

UpCat


People also ask

What is Route reload ()?

Using reload() method: Angular route service reload() method is used when we want just the current route to be reloaded instead of making our entire application reloading or refreshing.

What is use of $routeProvider in AngularJS?

We use $routeProvider to configure the routes. The config() takes a function that takes the $routeProvider as a parameter and the routing configuration goes inside the function. The $routeProvider is a simple API that accepts either when() or otherwise() method. We need to install the ngRoute module.

Which function is used to set up a default route in AngularJS?

$routeProvider is used to configure the routes. We use the ngRoute config() to configure the $routeProvider. The config() takes a function which takes the $routeProvider as parameter and the routing configuration goes inside the function.

What is ngRoute AngularJS?

If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module. The ngRoute module routes your application to different pages without reloading the entire application.


1 Answers

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();
    });
like image 77
Dmitry Evseev Avatar answered Sep 18 '22 10:09

Dmitry Evseev