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

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, set controllers in the templates.
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?
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

Comments

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.