How to call a function in AngularJs when route matches?
Asked Answered
H

1

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

Horsecar answered 5/5, 2013 at 11:39 Comment(1)
Could you give some more information on your application - you are referring elements that have not be explained in your question - perhaps a plunkr or fiddle too could be provided?Pothook
B
20

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();
    });
Birdt answered 5/5, 2013 at 12:42 Comment(6)
And how do I make my route /ticket work with and without ticketId paramter?Horsecar
It should work with 2 routes that use the same Controller, one with :ticketId param, one withoutWheatworm
Yeah, listen to @Wheatworm : you'll need 2 routes. Updated the answerBirdt
@Dmitry Evseev is this the best way to identify the right method to call when the URL changes, is there no better way? You are just checking if ticketId exists in the $routeParams, what if I have lots of URL with ticketIds ?Crissycrist
@Digitlimit if you have lots of urls having same parameter name tickerId but doing different logic, you'd better have a separate controllers for them. One controller with too much logic will be harder to maintain, scale and test.Birdt
@Dmitry Evseev Yeah you are right. I think with this github.com/angular-ui/ui-router, it will be more easierCrissycrist

© 2022 - 2024 — McMap. All rights reserved.