forked from angular/angular.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Best Practices
Dean Sofer edited this page Sep 9, 2013
·
21 revisions
-
Namespace distributed code
You shouldn't worry about prefixing internal code, but anything you plan to OpenSource should be namespaced- The
ng-
is reserved for core directives. STOP USING IT - Purpose-namespacing (
i18n-
orgeo-
) is better than owner-namespacing (djs-
origor-
) - Checkout ui-alias to remove 3rd party prefixes
- The
-
Only use
.$broadcast()
,.$emit()
and.$on()
for atomic events
Events that are relevant globally across the entire app (such as a user authenticating or the app closing). If you want events specific to modules, services or widgets you should consider Services, Directive Controllers, or 3rd Party Libs-
$scope.$watch()
should replace the need for events - Injecting services and calling methods directly is also useful for direct communication
- Directives are able to directly communicate with each other through directive-controllers
-
-
Always let users use expressions whenever possible
-
ng-href
andng-src
are plaintext attributes that support{{}}
- Use
$attrs.$observe()
since expressions are async and could change
-
-
Extend directives by using Directive Controllers
You can place methods and properties into a directive-controller, and access that same controller from other directives. You can even override methods and properties through this relationship -
Add teardown code to controllers and directives
Controller and directives emit an event right before they are destroyed. This is where you are given the opportunity to tear down your plugins and listeners and pretty much perform garbage collection. Sometimes expecting angular to do all the work isn't enough.- Subscribe to the
$scope.$on('$destroy', ...)
event
- Subscribe to the
-
Leverage modules properly
It doesn't benefit anything to slice your app across horizontals. Instead, group your code into related bundles:app.users
,app.projects
. This way if you remove a module, your app still works.-
app.controllers
,app.services
, etc are useless since removing one module breaks the app -
app.users
,app.projects
, etc allows you to group related components together - Spread route definitions across multiple module
.config()
methods - Modules can have their own dependencies (including external)
-