Where to use ng-controller with ng-include

1,057 views
Skip to first unread message

Aaron Newcomer

unread,
Oct 4, 2013, 7:12:19 AM10/4/13
to ang...@googlegroups.com
I was wondering if anyone could speak to the difference between using the ng-controller directive *on* the same element as ng-include as opposed to defining ng-controller *within* the ng-include template.

"on":
main.html: <div ng-include="myTemplate.html" ng-controller="MyController">...</div>

"within":
main.html: <div ng-include="myTemplate.html">...</div>
myTemplate.html: <div id="rootElement" ng-controller="MyController">...</div>


I can see a benefit to the "on" scenario when the template and controller are loosely coupled and the same template works with ControllerA, ControllerB, and so on.

If otherwise, though, I feel the "within" approach really highlights the dependent relationship between template and controller. To be honest, this is how most of my code ends up (1:1 controller-to-template relationships).

Though, I could see how the "within" approach would muck up scenarios where the template is inserted in a "non" ng-include'd way such as with a $routeProvider configuration or AngularUI Bootstrap $modal.open().

And (I could be wrong here), I think the "within" approach creates an extra, implicitly defined ng-include controller, whereas the ng-include controller is precisely the requested ng-controller.

I think I just talked myself into the "on" approach.

It's probably a non-issue, but I was curious what others thought.
Reply all
Reply to author
Forward
0 new messages