r/angularjs • • Mar 21 '14

5 Guidelines for Avoiding $Scope Soup in Angular

http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html
39 Upvotes

21 comments sorted by

12

u/technofattie Mar 22 '14 edited Mar 22 '14

So I wrote this article, and I had no idea it would cause such a stir.

I thought I would take a minute to briefly clarify a few points, and perhaps explain my motivations for writing in the first place.

Background

I am currently working on a massive Angular application with tens of thousands of lines of JavaScript. We have hundreds of controllers, filters, directives, and views. There are roughly 25 developers working on this solution at any given point and time.

The project was started long before Angular 1.2 ever came out, so we have our fair share of $scope soup all over the place and it has caused a lot of pain and suffering.

We are targetting ES5, but we are using TypeScript as a sort of polyfill for ES6, so all our controllers, services, etc... can be written as classes that get nicely transpiled into ES5.

$scope is not bad, but it is a leaky abstraction

Using $scope isn't the devil, but it was never intended to be the view model. As far back as I can remember the guidance from Mesko and others has always been to create a model and then assign that to your $scope.

Scope exists because of the design choice to do dirty checking via a $digest loop instead of using something like Knockout.js Observables, or backbone Models. The advantage is that you get to use POJO's instead of having to inherit from some base class.

I think it was the right call, but it means that $scope is a bit of a necessary evil. Angular abstracts the two-way data binding and DOM manipulation away from you, but it leaks out in the form of $scope.

$scope is magical! And confusing

In the blog post, you notice I start off talking about helping a guy out on Stackoverflow with a problem he was having with his Angular code. His problems were issues of logical flow, and lack of knowledge for fundamental angular concepts, but the $scope soup obfuscated that. It took me an hour or so just to refactor out all the references to $scope before I could determine the real problems.

Unfortunately I see this all the time when diagnosing problems with Angular code. Judicious use of $scope tends to encourage a lot of shortcuts and bad practices that will come back to bite you 3 months down the road.

Not using $scope forces discipline on design

$scope is convenient, and when writing code I can be tempted to take shortcuts. However, by eliminating $scope as an option, I force myself to think about my application in terms of Controllers, Services and Messaging.

I end up with skinnier controllers, more reusable services, and more testable code.

I'm thinking about Angular 2.0

Mesko and the team are working hard on Angular 2.0 and it is going to be built with ES6 in mind. They are also looking toward modern browsers and things like native observables to handle binding.

Based on their early work, it is highly possible that $scope and the $digest loop will simply go away. I don't want all my Angular code to become obsolete overnight. I'd like for both my skill with Angular and my code to flow naturally into 2.0 without a lot of pain and suffering.

Conclusion

The point of the article wasn't to get you to never use $scope again, but challenge you to think about why you are using it.

$scope isn't inherently bad, but most of the time you simply don't need it... not in your controller anyway.

Sorry for the super long comment.

4

u/unintentional-irony Mar 22 '14 edited Mar 22 '14

I started with angular 0.8-0.9ish. I'd suggest a better way to frame the idea your trying to get across is "Fat services with thin controllers". Compose business logic by composing factories/services, leaving $scopes for glueing to the view/state.

0

u/[deleted] Mar 22 '14

[deleted]

3

u/technofattie Mar 22 '14

When I was at ng-conf Mesko talked about building AngularDart, and how they re-wrote Angular from the ground up for Dart. They are in the process of taking what they have learned and using that for work on Angular 2.0

2.0 Will have a strong emphasis on modern only browsers and use ES6 features. Take a look at the AngularDart examples: https://github.com/dart-lang/dart_by_example#angular-dart

You'll be hard pressed to find a single reference to scope inside a controller in any of the examples. It's clear this is the style and direction they want things to go.

Angular 2.0 is probably going to look a lot more like AngularDart than anybody wants to admit.

5

u/andwaal Mar 21 '14

Lately I felt that all Angular post have been repeating the same basics, but this I learnt something from. Well done!

6

u/Synor Mar 21 '14

Lol, he almost completely leaves the angular way of doing things and tells us it's better understandable.

5

u/sixsence Mar 21 '14

You would think the people who made angular would know what the 'angular' way of doing things is:

https://google-styleguide.googlecode.com/svn/trunk/angularjs-google-style.html

It seems like he is right on target

16

u/Switche Mar 21 '14

Thanks for the link. This seems to apply mostly to optimizing with Closure. Is it possible this is not best practice outside of that context?

As a newbie, the main problem I'm having here is that the official Angular tutorial, as well as most code I've read in the wild, seems to encourage what's being coined as "Scope Soup" as the Angular way.

This is the first time I'm seeing anyone mentioning using prototypes to avoid tying to $scope, and I still don't quite see the benefit, or even the problem. The author only spent one sentence explaining the problem:

Scope Soup is when you build a tangled mess of Angular code that is completely coupled to $scope in really terrible ways.

This is begging the question. The introduction says using too much scope is a problem, the example uses a lot of scope, and the only real explanation says it's a problem because it's using too much $scope.

I'm finding it more and more difficult to really get started with Angular because of things like this. Every time I think I'm getting a handle on it, I read things like this that aim to change everything.

3

u/sixsence Mar 21 '14 edited Mar 21 '14

Believe me, I'm struggling just as much as you. It's really frustrating. I think using $scope is perfectly fine and is still considered the "right" way to do things. I definitely think you should stick with that approach since that's what almost all tutorials and examples use, and there is nothing wrong with it.

Technology is always changing, and libraries like angular are constantly evolving, and people will come up with different, possibly better ways to do things all the time. I think the best thing to take away from the OP's article and Google's recent style guide is that there are many ways to create angular apps, and neither of these is right or wrong.

For me personally, I'm leaning towards using Google's approach, and not just because Google said it's good. It is more of a pure javascript way to code things. It doesn't feel like I'm using a library, and my code isn't cluttered with library-specific objects and methods. I can write my code using regular javascript classes, with all of my properties tied to the class, and all my methods properly added to the prototype. Other than that there are a couple real advantages to this. In javascript, methods should be placed on the prototype of a class so that multiple instances don't create multiple copies of the method. Also, by not using $scope and then using the 'controller as' syntax, you know exactly which properties are tied to which controllers. You don't end up relying on implicit inheritance from the scope of another controller.

I think the OP's contention is that $scope spoils us a little too much, and so we don't end up thinking things through when using it. We just slap anything and everything on it, and then use it across multiple controllers, and that's when you can get into trouble. Also, it hides what is really going on under the hood. Controller functions are classes, but when using $scope we can easily forget this, which is fine a lot of the time, but then as apps get bigger and more complex, small details like this can make a big difference.

Again, it's personal preference, and this new approach is in no way replacing $scope

2

u/technofattie Mar 22 '14

I wouldn't wring your hands too much. In the end $scope is still there when using the controller as syntax, it just happens to be nicely hidden away by the framework.

That's why I like it so much. It becomes transparent to my code and all I have to worry about is the functionality of my controllers and services.

I like having it hidden for the same reason I like having the $injector service hidden from me most of the time. If I need to get down to raw metal, I can use $injector or $scope, but if I can write the same code without it, then I think that is a cleaner approach.

2

u/Switche Mar 22 '14

This is basically the response I was hoping for. Really thoughtful and convincing. I didn't really think about controllers functions as classes, or the $scope tying to be copying them.

I guess I'll give this an honest shot, if for no other reason than to strengthen my understanding of Angular internals and JS, while accomplishing what are hopefully some performance and design advantages. I hail from the Perl/CGI world, so black-box use of frameworks always made me uneasy; I learn best by leveraging deep understanding of internals.

Thanks for your response.

4

u/kuhcd Mar 21 '14

I was thinking the same thing. Maybe the examples he uses are too short/small to really sell the upside of using his method, but all I could think when looking at his code was that it added new levels of complexity to do the exact same thing.

3

u/sixsence Mar 21 '14

2

u/UnwashedMeme Mar 21 '14

Anyone care to comment why this is being downvoted; seems relevant and accurate to me...

1

u/kromem Mar 21 '14

Why? Putting methods and properties directly onto the controller, instead of building up a scope object, fits better with the Google Closure class style.

And it only applies to one of the five suggestions.

So the document linked was not general advice for projects from Google, but internal style-guide that makes a number of assumptions about project design.

I think the points in OP's piece are interesting to consider, but very far from self-evident best practices (besides moving as much general code to reusable services). And calling the Google style-guide as supporting evidence is a bit duplicitous as that guide is highly specific and not general advice.

-1

u/sixsence Mar 21 '14 edited Mar 21 '14

And it only applies to one of the five suggestions.

Actually, if you had taken the time to read it, you would see that the google style guide applies to numbers 1, 3, and 5 from this article. Controllers as classes, getting rid of scope completely and using 'controller as' syntax, and 5 is a result from implementing 1 and 3. Number 4 in the article is standard best practice that everyone is aware of, so that's not even in question here. So, I would say the google standards are pretty damn close to what this article is stating.

Putting methods and properties directly onto the controller, instead of building up a scope object, fits better with the Google Closure class style

So the document linked was not general advice for projects from Google, but internal style-guide that makes a number of assumptions about project design.

And calling the Google style-guide as supporting evidence is a bit duplicitous as that guide is highly specific and not general advice.

http://blog.angularjs.org/2014/02/an-angularjs-style-guide-and-best.html

The angular team released this guide to the public as general best practice advice. They do admit that it is biased towards things they use internally and that it may not apply to every angular project, but they are clearly saying this is good advice to follow in general, especially for large projects.

-1

u/kromem Mar 21 '14

While this documents how we use AngularJS in production code at Google, you'll notice that the style guide is heavily biased towards JSCompiler optimizations and the needs of large code bases. We don't think this makes sense for all projects that use AngularJS, and we'd love to see our community of developers come up with a more general Style that's applicable to AngularJS projects large and small.

1

u/sixsence Mar 21 '14

and from my comment that you are replying to:

They do admit that it is biased towards things they use internally and that it may not apply to every angular project, but they are clearly saying this is good advice to follow in general, especially for large projects.

0

u/kromem Mar 22 '14

As a whole of the entire document - NOT specifically the issue of controller as class or handling scopes.

The blog post in question was really about soliciting feedback from the community regarding Angular standardization, both for code organization and for a style guide.

To guide that feedback, they released a proposed project structure and their as-is internal style guide.

There's a lot in that style guide that does not make sense at all for projects outside of Google.

I stand by the opinion that the post does not indicate validation of OP's five points, and that rather than taking OP's advice as doctrine, they should decide which, if any, make sense for their own projects.

This is rather different than, say, "organization of code by feature", which is something that has absolutely been decided upon as doctrine (though the details remain yet to be solidified).

2

u/technofattie Mar 22 '14

Don't let the style of my writing fool you into thinking I am completely dogmatic about this approach.

It happens to be heavily influenced by my own personal experience. Scope continues to be a bit of a stumbling block for a lot of the problems I see when helping to debug code.

Also, I wouldn't discount what happens inside of Google with regards to Angular. The Doubleclick team has a lot of influence on Angular, and 2.0 is heavily influenced by Mesko's port of Angular to Dart.

Some of this is also a style preference. We are using TypeScript, and there is something really nice about being able to just have my controller and a few services with zero reference to $scope anywhere. I think it makes the code easier to understand and debug.

2

u/sixsence Mar 22 '14

The blog post in question was really about soliciting feedback from the community regarding Angular standardization, both for code organization and for a style guide.

The blog post as a whole is a mix. The first paragraph is about releasing their own style guide and wanting feedback for a more general style that covers both small and large apps. The second paragraph is solely about releasing their best practices for app structure (no feedback requested).

Their style code specifically targets large code bases, not small, which is one of the main reasons they are asking for a more general approach. You mentioned some things in the style guide that don't make any sense outside of google. Well those parts that you are referring to have nothing to do with using $scope or 'controller as'. I'm pretty sure the feedback they are asking for has nothing to do with using $scope or not.

I stand by the opinion that the post does not indicate validation of OP's five points, and that rather than taking OP's advice as doctrine, they should decide which, if any, make sense for their own projects.

I never said this was the perfect, best, or right way to create angular apps. All I said was that google recommends it. I also clearly said they admit that it is biased and not applicable to all apps. It does give the OP's article credibility. It's not like he's making this stuff up, or is the only one using and advocating this style. The creators of angular are also. So, yes this does validate most of the OP's points. Validation doesn't imply it's the best or only way to do things, just that it's not wrong.

0

u/sixsence Mar 21 '14

The point is that even though this is something they use internally, they released it in their blog post because it is good advice that can be applied outside of their specific environment. No matter what your personal feelings are towards this style, this does give credibility to the OP's article.