AngularJS & three.js - Service (Factory), Directive and Controller

Sunday, February 9, 2014 Posted by Josh Staples 0 comments

Encapsulate a THREE.js scene with an AngularJS factory:



My 3D tic-tac-toe game demonstrates how to inject a factory singleton of a WebGL scene into AngularJS directives and controllers.

This approach encapsulates the WebGL scene as a service factory.  Such encapsulation exposes access to the scene via the returned factory's  API. 

This API exposure allows you to dependency inject the 3D scene into any number of controllers and directives.   Note: a service factory in AngularJS is a singleton so there is only 1 copy of the scene being tossed around.

Encapsulation also allows you to isolate the scene-logic from your application-logic.  This will help your grand design.
You can use directives like 'click' and 'marquee' on the canvas element to allow for mouse interaction with the scene.

AngularJS Factory Features:

  • Singleton
  • Can be injected into controllers and directives
  • Isolates all three.js code from user and framework
  • Exposes API allowing DOM events, AngularJS and three.js code to interact
  • Allows you to create/destroy scenes
  • Manually start, stop render loop
  • Manual render for static scenes (no render loop)