Do you have to us ng-Controller in the view or can you just declare it in the $routeProvider?

后端 未结 3 1559
一整个雨季
一整个雨季 2021-01-14 12:19

I recently realized I had not used ng-Controller to declare the official scope of my controller in the HTML but had only mentioned it in $routeProvider and all APPEARS to be

相关标签:
3条回答
  • 2021-01-14 12:57

    If you're not rendering that HTML from a different place somehow (which I haven't seen happening thus far) then there's no difference, just make sure you're not declaring it twice by accident (once in the $routeProvider and another in the HTML).

    0 讨论(0)
  • 2021-01-14 12:58

    You should only declare the controller in your $routeProvider. Otherwise, it will be instanciated twice.

    In some case it would be transparent but it can easily lead to bugous behaviour.

    As a reference, the Angular guide provides code samples about how do use ng-view: https://docs.angularjs.org/api/ngRoute/directive/ngView

    0 讨论(0)
  • 2021-01-14 13:03

    I would consider it correct, and an advantage the way you have done it, because it better relates the context of your view and bound controller by keeping things in the one place.

    Just bear in mind that providing your controller in the route definition is basically the same as putting an ng-controller="MyCtrl" inside the element containing your ng-view directive that matches your route view.

    Also, if you need more complex routing (eg: hierarchical views and controllers), then I would consider looking at ui-router to use instead of ngRoute

    0 讨论(0)
提交回复
热议问题