georoot
georoot

Reputation: 3617

Passing variable name in angular route

Currently I am able to add routing mechanism in AngularJs with the following code :

App.config(function($routeProvider, $locationProvider) {
    $routeProvider
        .when('/', {
                templateUrl : '/templates/home.html',
                controller  : 'landing'
            })
        .when('/login', {
                templateUrl : '/templates/login.html',
                controller  : 'login'
            });
});

What I need is an url in the format like /app/:appname which should fetch template called /template/:appname.html. I know that the appname can be accessed from controller using :

$routeParams.appname;

But how can I render template based on that parameter ?

Upvotes: 3

Views: 1207

Answers (2)

Taku
Taku

Reputation: 5927

You could do this:

App.config(function($routeProvider, $locationProvider) {
    $routeProvider
        .when('/app/:appname', {
                templateUrl : '/templates/app-template.html',
                controller  : 'AppCtrl',
                resolve: {
                    appPath: function ($route) {
                        return $route.current.params.appname;
                    }
                }
            })
});

in AppCtrl,

App.controller('AppCtrl', AppCtrl);

AppCtrl.$inject = [
    '$scope'
    'appPath'
];

function AppCtrl($scope, appPath) {
    $scope.template = appPath + '.html';
}

in app-template.html, use ng-include as such

<div ng-include src="template"></div>

Hope this helps.

Upvotes: 1

huseyinozcan
huseyinozcan

Reputation: 86

templateUrl can be use as function which returns a url.

App.config(function($routeProvider, $locationProvider) {
    $routeProvider
        .when('/', {
            templateUrl : '/templates/home.html',
            controller  : 'landing'
        })
        .when('/:appname',{
            templateUrl: function(params){
                return "templates/"+params.appname +".html"
            },
            controller: 'Ctrl'
        });
});

Upvotes: 1

Related Questions