Structuring an angular app is one of the hardest things about learning angular. Angular tries hard to modularise code, but (the current state of) html, css, and javascript doesn't really allow you to package the things together, so you have to find a way that works well for you.
The way I keep things separate (yet together) is generally using my build system (I use gulp), and a CSS preprocessor (for me, Stylus).
My process for creating a new directive is as follows:
Define a new angular module (in its own file) my-albums.coffee:
angular.module('my-albums', [])
.directive('myAlbumDirective', ()->
restrict: 'A'
templateUrl: 'SomeTemplate.jade'
# etc.
)
Create a jade template my-album-directive.jade
.album
img(ng-src="{{album.imageUrl}})
span.name {{album.name}}
Create the stylus file with the same name as the module prefixed with an underscore: _my-albums.styl. In here I will include module specific css.
[myAlbumDirective]
.album
display flex
flex-direction column
@media screen and (min-width: 600px)
flex-direction row
Then, whenever I import an angular module into my app.coffee (which contains a long list of module imports), I also import its style in my main.styl stylesheet:
@import '../my-albums/_my-albums.styl'
When I run my build system, it (among other things):
- Automatically compiles
.jade files into a app.templates angular module (pre-populating the $templateCache (app.templates is included in the imports in app.coffee
- Compiles and concatenates all coffeescript into
script.js
- Compiles and concatenates all stylus files whose filenames do not begin with an underscore into
style.css
Then inside my index page I just have two imports:
script(src='js/app.js')
link(rel='stylesheet', href='css/style.css')
TL;DR:
There's no easy way of keeping your directive code separate from the rest of the page, but if you research build systems and other people's angular project structures, you'll find something you like.
Note
SoonTM things will be neater (see web components and angular 2.0)