1

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: '/'
        });
}]);
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
SmartFingers
  • 105
  • 1
  • 8

2 Answers2

2

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>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • Yes, set controllers in the templates. – Shashank Agrawal Feb 17 '16 at 04:30
  • 1
    Thank you very much! It really work! May I understand in this way: ngRoute will first include the template to the ng-view directive, and then all of other angularjs directive start working? And this is why the ng-app still works for the controller in templates? – SmartFingers Feb 17 '16 at 04:37
0

This is the best solution

http://ify.io/lazy-loading-in-angularjs/

And sample code is in github

https://github.com/ifyio/angularjs-lazy-loading-with-requirejs

Bear Vast
  • 150
  • 1
  • 8