This article also talks about this topic on the guide line #3. Take a few minutes and read that part of the article. Go ahead, I can wait.
Interesting, right? This feature helps a lot on your controller’s design and code maintainability, but let’s go one step further.
Let’s take the following controller and start to refactor it out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
… our html looks like this:
1 2 3 4 5 6 7 8
- Making the changes suggested by the article we end up with something like this:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
This looks better already, we are not coupled to the given
$scope object anymore. Decoupling is always good.
Hmmm, but now instead of a
$scope soup, we have a
this soup. Still not clear what is exposed and
as the controller grows, things get uglier pretty quick.
- At this point 2 things come to my mind:
- Tell the
savemethod which object to save, allowing angular itself to build the object for us with small DOM change.
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6
How does it look to you so far?
You can go further and wrap MyResource in a function making the controller even smaller. Taking logic out of your controller into another functions that can be injected into other controllers is a very good way to allow for code reusability on the angular world.
keep a very good structure. You have private attributes and methods/functions and the best: you avoid the
In the same way you saw the
$scope soup before, abusing the reserved word
this is also evil. Extending objects with
prototype also seems unnatural for me, use it just when there is no other option.
Let me know your thoughts!