3

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 ?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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'
        });
});

1 Comment

sorry but i can't accept more than one answer as correct. Both of the above are and working. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.