My advice for Angular and SASS
August 01, 2014
On a recent project, I was coming up with a style guide. I included these as tips, since they’re really just a collection of best practices I’ve incorporated or come up with having worked in a coffee script, angular, SASS stack for a couple years now.
Coffeescript / Angular
-
Use classes for controllers.
-
Because your classes are controllers, it’s almost never necessary to attach things to $scope.
-
CS should be minified for non-dev environments, so use the array syntax in module definitions.
-
There are plenty of Angular module types. Use them, and keep those concerns separate!
- Controllers, Services, Factories, Constants, Filters, Directives
-
Using jQuery directly isn’t necessary. Selectors can be gotten with
angular.element()
.- In case we swap out the DOM API at any point.
-
Coffeelint does the heavy CS style checking, but still, keep it clean and tight.
-
“Private” class methods should lead with an underscore.
-
Name a controller by purpose, i.e., NewToggle, and name the instance (
controllerAs
) name + controller, i.e., NewToggleController.
SASS
- Nesting more than three levels deep is stinky and should be avoided.
- Each file should have a containing block, with all styles and children elements nested under.
- You will never, ever need an ID. Classes and pseudo selectors FTW.
- Get hip to flexbox; it’s the future.
- When using flex, and it’s align and justify properties, you probably don’t need to float things.
- Pages, widgets and directives should get their own stylesheet!
- Don’t specify values in pixels (
px
). Use%
orrem
.
HTML / Templates
-
Break up your templates and import them with ng-include.
- It’s more reusable this way, and template importing is super fast since they’re compiled to JS strings (using a template caching plugin).
-
Directives are awesome and the best way to customize behavior of an element.
-
There’s a crazy amount of built-in Angular directives and filters. And they’re hard to find in the documentation.
Hey, I'm Ian. I build websites and write about what I learn as I go. Follow me on Twitter.