Angular JS Logo

I’ve been rebuilding one of my sites to use Angular, and had attached my controllers to several endpoints that returned a variety of data models.  I built the endpoints following the principle of single responsibility for returning the data, and expected to use the data as re-usable elements on the front end.

Because my template required the ability to disperse elements of some of the data on various parts of the page, I figured using the controllerAs functionality would allow just that.  As expected, by stacking several controllers at the top of the page, and naming them with the controllerAs syntax, I was able to do just that.

<!--Top of page-->
<div ng-controller="dailyOfficeReadingCtrl as reading">
<div ng-controller="dailyOfficeCollectCtrl as coll">
<div ng-controller="dailyOfficeCanticleCtrl as cant">
<!--Throughout the page-->
{{coll.of_day}}... and so on

Soon, however, I discovered a particular limitation; or, rather, not a limitation, just something that would cause me heartache down the road when it came to maintaining my code.  Some of the data elements were attached to an ng-repeat (like the readings), and so required a virtual template within the main template, which would mean that any time I changed the endpoint, I would have to manually update the “template” on every page that used it.  Not very satisfying, and definitely not modular.

Enter components.  All data elements are now wrapped in components, so that I can simply drop in something like


or like

<bible-reading type="ot" value="reading.type.ot.passage"></bible-reading>

and can update the attached component template in one location when it needs updating across all pages that use the component.

I think the controllerAs syntax is still useful for those times when the main template uses a reusable data element that needs to be displayed differently on each main template (like maybe profile data), but in my case choosing the modularity of components makes updating things across multiple pages a breeze.

One thought on “AngularJS choosing nested controllers vs components

Leave a Reply

Your email address will not be published. Required fields are marked *