Search code examples
javascriptangularjsangularjs-routing

How to select different template depending on different angular js route value


I have a route like this:

$routeProvider.when('/test/item/:item', {
            templateUrl: '/test/test.html'
            , controller: 'TestController'
        });

Now I want to load different templateUrl depending on different :item value, How do I do it in angularJS?

for example:

$routeProvider.when('/test/item/:1', {
            templateUrl: '/test/test1.html'
            , controller: 'TestController'
        });
$routeProvider.when('/test/item/:2', {
            templateUrl: '/test/test2.html'
            , controller: 'TestController'
        });

Thanks in advance.


Solution

  • templateUrl can be a function as well and you get the first argument will be route params:

    So you can do something like this:-

      $routeProvider.when('/test/item/:item', {
            templateUrl: function(param){
              return '/test/test' + param.name + '.html'
              /*if(param.name === 'somevalue'){
                return someurl;
              }
              return someotherurl;*/
            }
            , controller: 'TestController'
        });
    

    templateUrl – {string=|function()=} – path or function that returns a path to an html template that should be used by ngView.

    If templateUrl is a function, it will be called with the following parameters:

    {Array.} - route parameters extracted from the current $location.path() by applying the current route