Sharing models between AngularJS controllers

I am currently in the process of developing an application that will showcase various charts and controls to filter the presented data. I have structured the HTML page in a way that remains consistent throughout, leading me to consider creating an HTML template that can be used with different controllers. Each controller would correspond to a specific chart type or set of filters for a particular chart.

My initial idea was to create a default HTML template which could be filled with the appropriate chart controller and filter controller based on the requested type.

To implement this concept, I decided to heavily rely on prototypical inheritance. I constructed a ChartController that establishes two scope models for holding the chart and filter control configurations. Subsequently, I developed child controllers like LineChartController and LineChartFiltersController to populate these variables with type-specific configurations.

Although everything is functional, I have reservations about this approach since the child controllers are heavily reliant on the parent controller. This dependency makes testing and understanding the source of $scope models challenging for individuals unfamiliar with the controller design.

Here are some code snippets:

app.controller('ChartController', ['$scope', function($scope) {
  $scope.chart = {};
  $scope.filters = {};
}]);
app.controller('LineChartController', ['$scope', function($scope) {
  $scope.chart.tooltip = {...};
  $scope.chart.commonSeriesSettings = {...};
}]);
app.controller('LineChartFiltersController', ['$scope', function($scope) {
  $scope.filters.beginDate = ...;
  $scope.filters.endDate = ...;
  $scope.filters.granularity = ...;
}]);

A route has been configured to redirect to the HTML template shared among all charts, utilizing the ChartController. Within this template, I incorporate both LineChartController and LineChartFiltersController to establish the parent-child relationship:

<div ng-include="/partials/line_chart.html"></div>
...
<div ng-include="/partials/line_chart_filters.html"></div>

line_chart.html

<div ng-controller="LineChartController">
  <div chart="widget"></div>
</div>

line_chart_filters.html

<div ng-controller="LineChartFiltersController">
  <!-- date pickets, sliders, etc. that use $scope.filter -->
</div>

While I understand that using a service to share data between controllers might be a better approach, my intention is to exchange model data such as chart configurations and filter controls rather than fetching business models from a server. I find it difficult to see the benefit of services in this scenario because a service provides a singleton object. Personally, I anticipated receiving individual instances specific to instantiated controllers similar to conventional OOP programming. Hence, I opted for scope inheritance.

Would there be another method to accomplish my objective effectively? Or should I reconsider utilizing a service for this purpose?

Answer №1

I have observed three distinct approaches to achieving a similar goal. Without full knowledge of your specific use case, it's hard for me to determine which method would be most suitable for you.

Here are three strategies that I am familiar with:

  1. Utilize a Custom Directive to retrieve and display information consistently. Keep in mind that this may not be ideal if the listing varies between pages.
  2. Develop a Service to manage the logic and state of shared information across controllers. This approach is effective when emphasis is on managing data and states rather than uniform display.
  3. Employ Observers for inter-controller communication. While useful for frequent event triggering, I caution against this method due to its challenging nature for testing. It's best suited for situations where multiple actions need to be triggered frequently.

Providing some code along with your query could provide more clarity. Thank you.

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

Is there a way for me to import a variable from one file and use require() to access it in another file?

This is my current folder structure: collegesapp -- |-- node_modules -- express | -- connect | -- jade | -- passport |-- routes -- routes.js ...

Using Python Selenium to create a login page with Javascript

Attempting to access a page using Python selenium package for certain activities is proving challenging. Despite the following code being written, an error message of "the Class is not found" keeps appearing. To proceed with using send_keys(), it's ne ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

Can VueJS Computed handle multiple filters at once?

I am encountering an issue with this code - when I attempt to add another filter inside the computed section, it doesn't work. However, if I remove the additional filter, the code functions correctly. My goal is to have both company and product searc ...

Retrieve all web elements selected in Selenium and store them as a List

Unique Question: How can I obtain the <select> web elements themselves as a List in Java, without focusing on the contained <option> tags? The resulting list should contain two elements. The only method I came across is driver.findElements(), ...

Node.js Express not inserting data with Mongoose when using form data

For the past two weeks, I have been struggling to post data to insert into a database using form-data. It consistently shows a 400 bad request error. Below is my code for server.js: require('./db.js') let express = require('express') ...

Guidance on editing list items individually using jQuery from separate input fields

Working with li presents some challenges for me. On my webpage, I have an input field that dynamically adds values to a list. However, the function to edit these values is not working properly. After editing an li element, it deletes all classes and span ...

JSON data not displaying correctly in bootstrap table

I've been grappling with this issue for hours now, but I'm struggling to get my bootstrap table populated correctly. Here's the snippet of my HTML: <html> <head> <link rel="stylesheet" href="https://code.jquery.com/ui/1.1 ...

Changes made to the data are not reflected in the user interface, but they are visible in the console

When working on a React project with input fields, I encountered an issue where the date data can be changed but doesn't get reflected in the UI. Instead, the updated data is visible in the console. The code snippet below showcases how I'm using ...

When async is set to true in an Ajax call, the response may come

I recently developed a function that works perfectly fine when the async option is set to false. However, I am now looking to achieve the same functionality and return value but with async set to true. function Call(param, proc) { var url = "../../ ...

The AJAX request successfully retrieves data, but the page where it is displayed remains empty

I have come across similar questions to mine, but I have not been successful in implementing their solutions. The issue I am facing involves an AJAX call that is functioning correctly in terms of receiving a response. However, instead of processing the re ...

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

Ways to transmit data from PHP to JavaScript

I have a file called "hotlaps.php" where I've created a JavaScript script: echo "<body onload=\"myFunction(".$array_1.",".$array_2.",".$array_3.");\">"; In my "hotlaps.js" file, I have the following function: function myFunction(arr ...

"What is the proper way to add a new row to a database utilizing AJAX and the MVC framework in C#

I am currently facing an issue with adding a new row into my database using C# MVC AJAX. Despite seeing the textbox value as a parameter in the URL, when I attempt to submit by clicking the button, it fails to work and I am unsure of how to proceed in reso ...

Turn off Babel's strict mode when transpiling JavaScript files

Currently, I am facing an issue while trying to transpile a set of JavaScript files using Babel. Since Babel operates in strict mode by default, it triggers a syntax error whenever there is a conflict like the use of the delete keyword. The solution I am s ...

Attach the Bootstrap-Vue modal to the application's template

I am implementing a custom modal using bootstrap-vue modal in my project on codesandbox. This is the template structure: <template> <b-button variant="link" class="btn-remove" @click="removeItemFromOrder(index)"> Remove item </b-bu ...

What is the process for reversing styles on the second click?

This is the script I've written: function displayPanel(index, colorCode) { buttons.forEach(function(button){ button.style.borderBottom=""; }); tabButtons[index].style.borderBottom="none"; panels.forEach(function(panel){ ...

The boxslider plugin is malfunctioning when accessed in Sitecore's preview mode

Even though the Boxslider plugin works when we view the page in a browser, it fails to function properly when the same page is viewed in Sitecore's Preview mode. This issue can be replicated by navigating to Presentation in the top menu, then selectin ...

Display images in a list with a gradual fade effect as they load in Vue.js

In my Vue project, I am looking to display images one at a time with a fading effect. I have added a transition group with a fade in effect and a function that adds each image with a small delay. However, I am facing an issue where all the images show up ...