Skip to content Skip to sidebar Skip to footer

Angularjs, How About Multiple Routes With Different Templates But The Same Controller?

i'm investigating if i can have what the title says. Here's my thought. Let's assume that i've got this routes: .when('/', { templateUrl : 'partials/homepage.html', })

Solution 1:

One solution could be the following one:

angular.module('myapp', []).
            config(['$routeProvider', function($routeProvider) {
            $routeProvider.when('/:templateName/:pageId', {
                templateUrl: function(urlattr){
                    return'/pages/' + urlattr.templateName + '.html';
                },
                controller: 'YourCtrl'
            });
        }
    ]);

From the AngularJs 1.3 Documentation:

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.<Object> - route parameters extracted from the current $location.path() by applying the current route

Solution 2:

I would move your singleton logic from your controller to a service. Since you didn't provide much code below is an example to give you an idea how it could work.

app.config(function($routeProvider) {
  
  $routeProvider
    .when('/', {
      templateUrl: 'partials/homepage.html',
      controller: 'SingleController'
    })
    .when('/test', {
      templateUrl: 'partials/test.html',
      controller: 'SingleController'
    })
    .when('/page/:pageId', {
      templateUrl: 'partials/page.html',
      controller: 'SingleController'
    });
  
});

app.provider('appState', function() {
  
  this.$get = [function() {
    return {
      data: {}
    };
  }];

});

app.controller('SingleController', function ($scope, appState) {
  
  $scope.data = appState.data;
  
});

But if it must be a singleton controller you actually could use the ng-controller directive before your ng-view directive so it becomes a $rootScope like scope for all your views. After that just add empty function wrappers in your $routeProvider for the controllers.

Post a Comment for "Angularjs, How About Multiple Routes With Different Templates But The Same Controller?"