Wednesday, 28 August 2013

Inheritance and nested views in AngularJS

Inheritance and nested views in AngularJS

I'm trying to set up some nested views in angularjs. I've been using the
ui-router library to do this which works great for the most part. The
problem is that there is a separate controller for each view with no real
inheritance going on between them. If I want to modify something in a
parent controller from a child controller I have to use $scope.$parent .
This is a bit of a pain and it can become worse if there are multiple
levels of inheritance and you have to remember which level the variable
you are accessing is on. Also if you forget to use $parent in your child
controller and you try to modify one of the parent's variables, Angular
will create a new instance of the variable which could lead to some hard
to track down bugs.
Ideally I would just be able to use prototype inheritance. This would also
map nicely into classes in Typescript or Coffeescript. One way I thought
of to do this would be to get rid of all the parent controllers and just
have the child controllers which would inherit any common functionality
from prototypes (super classes). Then you would just have to throw the
controller up on the $rootScope so that the parent views could access it.
Can anyone think of any issues with this solution or better solutions?
Would I be better off just using $parent and letting Angular handel the
"inheritance".
Thanks

No comments:

Post a Comment