Interacting between Angular controllers and directives while maintaining separation of concerns

In my AngularJS project, I've implemented a directive within a module named ThreeViewer that displays WebGL scenes based on the specified source file. The code snippet below outlines the basic functionality:

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: '='
    }
  }
}])

The current functionality successfully loads the scene, saves it to the scope, and passes it to the renderer. Now, I'm looking to incorporate user interaction, such as object rotation, by creating a controller. However, I'm unsure how to approach this while maintaining Angular's principle of separation of concerns. How can the controller work independently of the directive and vice versa, without direct dependencies on one another? Should the controller avoid directly modifying the scope.scene object? If so, how can this be achieved?

One potential solution could be to have the controller perform generic actions like rotation without specific knowledge of the object, and then find a way for the directive to interpret and apply these actions. Alternatively, is it acceptable for the controller to directly edit scope.scene? If so, how can this communication be established?

Answer №1

To streamline the process, I suggest creating a separate service for scene logic, such as loading and parsing data. You could even have multiple services, one for json parsing and another for tasks like rotating. It's ideal for a controller to pass the scene object to a service without containing specific logic, as its main role is to facilitate communication between the services and the view.

To properly define the scope, consider instantiating a SceneController within the directive using the controller and controllerAs parameters, and then attaching the scene to this controller. This way, the SceneController becomes a dedicated controller for enhancing the view and providing controls for the scene.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract JSON data from a web address using JavaScript

A unique system has been created to parse JSON and style it using CSS. Instead of outputting the data within the script, the goal is to retrieve data from a local or remote URL. <script type='text/javascript'> $(window).load(function(){ va ...

Tips for examining a rate-limited HTTP request function

I am trying to test a naive rate limiter I implemented in Node.js for making HTTP requests to an external service. The service has a limit of 10 requests per second, and I am facing timing issues with my current implementation. Despite being aware of the i ...

Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a ...

In JavaScript, a variable's value can be assigned to another variable using the variable

I have a collection of predetermined variables. I dynamically assign a value to another variable, which ends up representing the name of one of the predefined variables. This allows me to easily determine which set variable to use on a particular section o ...

Determining the size of each element in an array using Angular

Can someone help me figure out how to count the number of times "Jack" appears as the winner in my array? I need to return this count. function myCtrl($scope) { $scope.data = [{ game: 1, dnscore: 10, bwscore: 9, winner ...

Error: Attempting to access the 'state' property of an undefined variable within the bootstrap framework

While attempting to update the state value, I encountered an error stating TypeError: Cannot read property 'state' of undefined. This error occurs when I enter something in a field and then click submit. As a newcomer to React, I realize this may ...

Encountering issues with app functionality following update to Ionic RC4 version

Since upgrading from Ionic rc3 to rc4, I've been facing difficulties running my app smoothly. The app compiles without any errors when I use ionic-app-scripts build --prod, but when I try to run it on my iPhone, all I get is a blank screen and an err ...

"encountered net::ERR_NAME_NOT_RESOLVED error when trying to upload image to s3 storage

I am currently developing an application using Angular. I have been attempting to upload a picture to my S3 bucket, but each time I try, I encounter this error in the console. https://i.stack.imgur.com/qn3AD.png Below is the code snippet from my upload.s ...

updateStatusCallback function is not defined in the Facebook example using jQuery

I've been trying to incorporate Facebook integration into my HTML code, specifically adding features like Facebook login and sharing functionalities. However, I've hit a roadblock in the process. Even after searching extensively for solutions, I ...

`Considering various factors to alter class pairings`

I have defined a few style classes in my stylesheet as shown below: .left-align{ /* some styles here */ } .right-align{ /* some styles here */ } .validate-error{ /* some styles here */ } Depending on the type of data, I need to align the content ei ...

Updating the Position of an Element in ElectronJS (e.g. Button, Label, etc)

Is there a way to change the positioning of a button in a window using JavaScript and Electron? I am trying to create new input boxes next to existing ones, but they always appear below the last one created. Is it possible to specify x and y coordinates fo ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

Frontend and backend collaboration: encountering a 404 error with the Koa proxy

I have a backend Node application that I would like to connect with a frontend AngularJs app. Both the backend and frontend are part of the same repository but sit in different folders. The Node app is functioning properly, and I can successfully interact ...

How do I find out the properties of individual components in Material UI?

Learning material ui has been a challenge for me as I struggle to figure out the properties available for each component. For instance, in a tutorial on YouTube, they used the AppBar component like this: <AppBar title="Enter user details" /> But ho ...

Failed to retrieve information using a custom header in the HTTP request

My AngularJS code works well without the header option. $http.get(env.apiURL()+'/banks', { headers: { 'Authorization': 'Bearer '+localStorageService.get('access_token') } }) Here is the request: OP ...

tilt and give motion to image within canvas

I am looking to incorporate skewing and animation effects on an image displayed on a canvas. While I have successfully drawn the image on the canvas using the code snippet below, I am unsure about how to apply skewing and animation to the image post-drawin ...

Nested loops seem to override previous results with the final output

I am attempting to iterate through an array of months nested within an array of 'years' in order to calculate a count for each month using a custom angular filter. Initially, I set up the structure I will be looping through in the first while loo ...

Can $event be transferred from cshtml to Vue.component?

I am facing an issue when trying to pass an event into my Vue component. No matter what method I try, I keep getting a "TypeError: Cannot read property 'preventDefault' of undefined" error. Here is the code snippet for my Vue component: Vue.com ...

How can you disable listeners and minimize performance impact in concealed React components?

In order to meet our requirements, we need to display the same react component in various positions on our grid and toggle their visibility based on screen width. For example, our product module component will be displayed at position 3 on mobile devices a ...

The jQuery($) function cannot be accessed within the module file

I have been utilizing webpack to consolidate my code. The following excerpt is from my main.js file where I am including jQuery. main.js var $ = global.jQuery = require('jquery'); $('someSelector').on('rest of the code.& ...