Dynamically set controller for view using ngRoute in AngularJS

389 views Asked by At

I'm using params to dynamically route URLs to different HTML.

Is there any way I can set different controllers for those views? Or I should separately route them and use controller and controllerAs to set controller?

Since all of the templates are totally functionally different, is it right to do in this way? I know in more general case, such a way is only used for the restful query. If no, is there a better way to route different URLs to the different template?

angular.module('application',['ngRoute'])
.config(['$routeProvider',function($routeProvider){
    $routeProvider
        .when('/',{
           templateUrl: 'src/app/other/homepage.html'
        })
        .when('/:category/:page',{
            templateUrl: function(params) {
                return 'src/app/'+params.category+'/'+params.page+'.html';
            }
        })
        .otherwise({
            redirectTo: '/'
        });
}]);
2

There are 2 answers

2
Shashank Agrawal On

Instead of defining controller in your router mapping, just define them in your HTML using ng-controller.

Now, each view or the HTML will be responsible for initializing the controller.

Like for: src/app/fruit/apple.html (when you browse: /fruit/apple)

<div ng-controller="AppleController">
   <!-- Apple content -->
</div>

for: src/app/fruit/orange.html (when you browse: /fruit/orange)

<div ng-controller="OrangeController">
   <!-- Orange content -->
</div>
0
Bear Vast On