angular / angular.js

AngularJS - HTML enhanced for web apps!
https://angularjs.org
MIT License
58.81k stars 27.49k forks source link

ng-controller as not working with $scope #8187

Closed betonetotbo closed 10 years ago

betonetotbo commented 10 years ago

$scope service is not working when you use a Controller with alais.

See the code: http://plnkr.co/edit/FGPQxaUY58D5OFGGuU9Z

hollanddd commented 10 years ago

This is expected when aliasing controllers. Use 'this' instead of '$scope' when aliasing.

caitp commented 10 years ago

@betonetotbo, @hollanddd is correct here. "controller as" syntax doesn't mean "this === $scope", it really just means the controller's "this" is put in scope with a particular name. There's still a distinction between $scope and the controller itself.

betonetotbo commented 10 years ago

Ok, thanks for reply.

Ps.: for me this makes no sense. The concept of an "alias" is to identify the "scope" of the projection. If I want to use 2 or more controllers nested, how can I distinct they? I need to use the "this" and forward it with "var scope = this" for futures.

caitp commented 10 years ago

@betonetotbo:

different controllers have different this values, since they're instantiated seperately. They are distinct in scope via their alias names (EG $scope.users vs $scope.articles) and could be used in views distinctly via users.me.name vs articles.top5(), this would work perfectly.

If one controller needs to look at another controller's contents (you should not do this), a good solution would be to use a service to share data --- but otherwise you could use the aliased names in scope, or the jqLite controller() api to get the controller you want.

I don't think this is really a problem, it seems to be more just a misunderstanding of whats happening. The alias does not identify the scope, it identifies the controller.