Angular: controller-directive interaction with separation of concerns

255 views Asked by At

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?

1

There are 1 answers

0
LionC On BEST ANSWER

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 a conroller passing the scene object to a service, it should just not contain specific logic for it, as its role should just be to mediate between services containing logic and the view.

For scoping, I would instantiate a SceneController(e.g.) for the directive with the controller and controllerAs parameters and attach the scene to that controller. This way the SceneController is a specific controller to provide a rich view and controls for a scene.