A few months back I read this article about not using ng-controller and adopted the idea behind it: that angular apps should be sets of components working together.
The basic idea was that you would use isolate scope directives with their own controllers like this:
.directive('myAppContestantList', function() {
return {
scope: {},
templateUrl: 'my_app_contestant_list.html',
replace: true,
controller: 'ContestantListCtrl',
controllerAs: 'ctrl'
};
})
.controller('ContestantListCtrl', function() {
this.contestants = [
{firstName: 'Rachel', lastName: 'Washington'},
{firstName: 'Joshua', lastName: 'Foster'},
{firstName: 'Samuel', lastName: 'Walker'},
{firstName: 'Phyllis', lastName: 'Reynolds'}
];
});
and instead of making your a data property of $scope
in your controller, you made it a property of this
(this
being the controller itself). Defining variables on the controller meant you could reference your data in your html just by prefixing your data with ctrl
because that's what you put in the controllerAs
field:
<li ng-repeat="contestant in ctrl.contestants">
{{contestant.firstName}} {{contestant.lastName}}
</li>
This worked perfectly fine for me, and I began nesting directives instead of nesting controllers, which solved the nested $scope
problem.
Given that background, what I don't understand is why the article advocates defining variables on your controller instead of on $scope
. It's true that previously $scope
was a huge problem because once you had nested scopes it would be a mess, but using the pattern it advocates of isolated scope directives, variables defined on $scope
never leak.
You would also never find yourself in the position where there would be more than one controller in the template so controllerAs
seems useless as well.
I say this after being very successful using the pattern for a few months with variables defined on my controller. I'd just like to know if/why it's better to do that than define them on $scope instead of blindly following along with the article.
Does it possibly have to do with bindToController
?
Could someone point me in the right direction?