Google analytics script

Latest jQuery CDN with code tiggling.

Friday, 30 January 2015

Data binding a single shared view to different controllers using "ControllerType as instanceName" syntax

If you haven't already I strongly suggest you first read John Papa's AngularJS styleguide. It's a magnificent document of an evolving set of AngularJS development best practices. Among them there's also one that says to abolish $scope use and rather provide view model data as part of controller instance because view bindings become more contextual amid other reasons. To accomplish this you need to use the ControllerType as instanceName syntax. This is usually a blessing but sometimes it may seem to be a curse especially when you give controllers contextual instance names (i.e. UserController as user) instead of some common name (i.e. UserController as vm). This is especially useful if you're nesting controllers and don't want to access parent controllers using scope's $parent property.

Contextual instance naming plays along nicely until you introduce shared views. Now when you want to bind your shared view to a controller instance you don't really know its name. It can be any controller instance name that will be using this shared view. Now what?