I have an AngularJS module that defines a nice directive that can show a WebGL scene from the scr="filename"
attribute. That works well and (snipped here and there) looks roughly like this:
angular.module('ThreeViewer', [])
.directive('three', ['$http', function ($http) {
return {
link: function (scope, element, attr) {
scope.renderer = new SceneRenderer(element[0])
$http.get(attr.src)
.success(function (json) {
var loader = new THREE.ObjectLoader()
var scene = loader.parse(json)
this.scene = scene
this.renderer.setScene(scene)
}.bind(scope))
},
restrict: 'AC',
scope: {
src: '='
}
}
}])
So what it does is load the scene, save it to the scope, and pass it to the renderer. This works.
Now I want to create a controller so the user can interact with the data, say to rotate the object. My question is how should one approach this, while adhering to the Angular paradigm of separation of concerns? It is my understanding that in Angular the controller should be able to work without the directive and vice versa -- without knowing anything about each other. Does that mean that the controller cannot directly modify the scope.scene
object? Then how does one go about it?
Just as a guess, should the controller just "rotate" without knowing what it is rotating? And then how should the directive pick this up?
Or alternatively, is it perfectly fine for the controller to edit scope.scene
? Then my question is how do I break it out of isolation?
I would put the scene-logic (including the loading/parsing) into an own
service
(or multiple, one for the json-parsing and one for rotating etc). I see no problem with aconroller
passing thescene
object to aservice
, it should just not contain specific logic for it, as its role should just be to mediate betweenservice
s containing logic and theview
.For scoping, I would instantiate a
SceneController
(e.g.) for the directive with thecontroller
andcontrollerAs
parameters and attach the scene to thatcontroller
. This way theSceneController
is a specificcontroller
to provide a rich view and controls for ascene
.