Working With Inherited Collections In AngularJS
In an AngularJS application, $scope instances are all part of a prototypal chain. That is, every $scope instance (except $rootScope, I believe) has, as its prototype, the $parent scope. This is a brilliant way to architect the view-model because it means that data loaded in one controller can be accessed by controllers (and views) farther down in the same $scope chain. But, does the "visibility" of this data imply anything about which controllers should modify this data? From a functional standpoint, no - any controller that sees a $scope value can mutate that $scope value. But, from a philosophical standpoint, I'm starting to believe that inherited data should only be directly modified by the controller that owns it.
NOTE: What follows may not play nicely with ngModel - when thinking about this stuff, I did not really consider how ngModel works.
Last week, I blogged about variable access in sub-classed components. In the blog post, which was inspired by the book, Fundamentals of Object-Oriented Design In UML by Meilir Page-Jones, I discussed the idea that a sub-class should only reference those properties and methods of its super-class that the super-class has already exposed publicly. In other words, a sub-class should never access the private variables defined in the super-class. Doing so creates a very tight coupling between the sub-class and the actual implementation of the super-class.
After looking at the super-class/sub-class relationship, I wondered if the same kind of philosophy could be applied to the prototypal $scope chain in AngularJS? In a recent MTV Meetup, Misko Hevery did talk about the "access philosophy" of the $scope object; but, he talked about it in terms of View vs. Controller. That is, the View should treat the $scope as read-only and the Controller should treat the $scope at write-only.
Now, Hevery doesn't speak to my question exactly, but he does point out the non-symmetrical behavior of the $scope. My question adds a constraint to this, asking if the same non-symmetrical behavior should be applied to different Controllers in the same $scope chain?
As I write more and more AngularJS, I find that my biggest problem is that some Controller will modify some $scope data and some of my other, relevant Controllers will never find out about this change. Sure, I can start adding $watch() statements to see if something specifically has changed; but, when I start dealing with things like cached data or things like collections, the $watch() statements either become too computationally expensive (ex, a deep-compare of an array) or they simply fail to catch all changes.
I'm starting to realize that if I lock down $scope mutation to its given Controller, I can maintain a singular source of truth which facilitates the broadcasting of data mutations throughout the $scope chain. Now, this doesn't mean that other controllers can't mutate "inherited $scope;" it simply means that those controllers have to ask for the mutations rather than applying them directly.
To codify this, let's look at an example with several levels of $scope and controller. Imaging that, in the root of my application, I have a collection of friends. This collection is then broken-down by gender. And, in each gender breakdown, a friend can have his or her gender toggled, which will transfer that friend between gender lists. Also imagine that I have a form that can add new friends to the collection.
This gives us the following scope/controller combinations:
- .... Male Friends
- .... .... Friend
- .... Female Friends
- .... .... Friend
- .... New Friend Form
Since the friend collection exists in the root $scope of the application, it implies that every single one of the above controllers can change it; but, I'm saying that they shouldn't. I'm saying that any time a friend needs to be added, edited, or deleted, the local controller should make this change through a message passed up to the root $scope - the scope that "owns" the friend collection.
Let's see this in code - it's a good deal of code, so you may be better off watching the video:
Some of this code is more complicated and distributed than it may need to be; but, in a small demo, it's hard to describe a scenario in which there are many nested controllers all making some use of shared data. That said, notice that none of the controllers ever changes data that it doesn't "own." The FriendController handles only the ngRepeat-related data; the FormController handles only its ngModel data; all mutations related to the core Friends collection are made through the root $scope and its controller.
Then, instead of dealing with $watch() statements which execute [potentially] many times in every $apply/$digest lifecycle, the root $scope simply $broadcast()'s when changes have occurred. This allows all "sub" controllers to know when the Friends collection has changed and they can react accordingly (ie. updating their gender-based breakdowns, in my demo).
My approach to sharing $scope data across nested controllers has definitely evolved greatly over time (and continues to do so). And, while this approach might feel like it has more overhead, the huge advantage is that it keeps controllers and $scope objects more loosely coupled. This means that changes made to one controller have a much lower chance of requiring parallel changes to be made in another controller.
Want to use code from this post? Check out the license.
I have a question. In your form controller you do
So this form controller assume that it's parent had a addFriend method. Looks weird to me but I'm not an angularJS expert yet
The "poor" analogy would be that "$parent" is like calling "super" in an inheritance relationship in an object-oriented language. In this case, the form knows that the root Controller has exposed a public method called "addFriend()". The problem is, the form also wants to have a method called "addFriend()." So, in order to have two different methods with the same name, the FormController has to pass the action up to the root controller via $parent.
Keep in mind that if the method in the FormController was something more unique, like submitForm(), we wouldn't have to do this:
In this case, since there is no name conflict, there is no need to call $parent since the request for "addFriend()" will automatically search the $scope chain.
Nice post, I have not read much about AngularJS, but if I wanted the method
accessible for both controllers in a way that was not necessary to repeat the code, just change the parameter (F or M), how could it be done?
I think in AppController.
Great post. Thanks.
One question: Why you name addFriend methods in form controller and app controller with the same name. I mean how you go about testing this. This might cause confusion. What if you name the one in form ctrl differently so that when you call addFirend anywhere on the scope, I know there will be only one addFriend and I don't use $parent on $scope. Or am I missing something here?!
Good question - that was also bothering me when I wrote the code. Yes, I could have moved it up into AppController. The reason that I didn't for this demo was that I didn't want the AppController to know that "Friends" was going to be broken down by gender; I wanted that information to be located only at the next level down of Controllers.
If I were writing this in a real app, I probably would have dont that - moved a gender-based function up into the $scope that *also* had the "friends" collection.
It might also be interesting to make a "class" for FriendCollection and then give it instance methods for breaking the collection apart. But, I haven't done much code like that, so I can't really say much about it.
You are right - it is confusing. I should have just named it "saveForm()" or "submitForm()" or something to that effect. Then, the saveForm() method could have simply validated the form data and made a direct call to $scope.addFriend() and not had to do anything tricky with the $parent reference.
I actually just ran into this same situation with a demo I was putting together.
Your implementation of multi-lvl $scope's > Mine
The relationship of $scope values is definitely an interesting thing! But it's not simple - it really forces you to understand prototypal inheritance, which is not at all a simple topic! Glad you like my example :D
I recognize the applicability of your solution, and how easy it makes to share data across multiple views or even "submodules" of rather simple application. But it seems to me that it creates a relationship between sub-parts of the application tighter than it should.
Perhaps sharing information among units would be better achieved through services designed to be independent of any scope hierarchy.
The best article about scope and prototypal prototypical inheritance in angularjs is http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs
It definitely creates coupling between the controllers in so much as the sub-controller is depending on the "public api" exposed (via the $scope) by the super-controller (so to speak). But sometimes, I think controllers are designed to work in conjunction. Take, as an example, a controller on an ngRepeat - definitely this is coupled to the data that view is providing in the ngRepeat expression, which is based on data provided by a controller higher-up.
Or imagine a "toolbar" that is part of a UI - you may want to add a controller to the toolbar simply to make interactions a little easier to orchestrate; but, the toolbar controller still depends on its parent View and controller for data.
Typically, I do try to make the controllers as decoupled as possible. And, as you suggest, having two different controllers talk to a Service can definitely help with this. I'm still learning about all this as I go - much of this post is a reaction to things that I have done "wrong" in the past :)
Dang - that was a good article! Awesome graphics explaining when a reference points to one scope vs. another scope. Great find!
Hey Ben, nice technique you've brought up.
I'm building an app using Angular at the moment, and I'm still figuring out wether to use inherited scopes, or services for the data handling.
One point I was wondering about, when I went through your article and the docs is, there is also an $emit function, allowing a child controller to emit events upwards, to parent controllers. Thinking about your example using $scope.$parent.addFriend(), the $emit function might be a way to reduce coupling between the two controllers.
Have you tried this yet, and if yes, have you been able to make it work similar to your example?
I thought about emitting an 'addfriend' event with arguments attached, and have a parent controller catch that event and handle it.
Sweet and Excellent way to explain the encapsulation issue.
I am a backbone programmer and it was very difficult for me to map the backbone's model/collection to the angular controller.
Now, I see the point, though the controller has the power to change a data, we should not do that, instead the controller have to trigger events and appropriate controller should handle the changes.
Thus, we can give the encapsulation just like backbone gives us. ;)
Yes I think this controller nesting is the right approach, providing access to $watched properties. Ember has a concept called 'itemController' that imitates the same thing except with the option of declaring this on the parent controller, for example MyArrayController.itemController = MyObjectController, or using your example MaleFriendsController.itemController = FriendController