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

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Could not complete operation: EPERM error indicating permission denied for 'stat' operation

Recently delving into Firebase Functions for my Flutter project has been a game-changer. Discovering the code generator, firebase_functions_interop, that seamlessly transforms Dart code into Javascript has made developing cloud functions in Dart a breeze. ...

Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema: const userSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, email: { t ...

Issue with AngularJS where the value in a dropdown list does not bind to ng-model if there are no changes made

Please check out my plunkr for reference: https://plnkr.co/edit/QRQQmxf3ZDyh6o0CqtrD?p=preview I have a form with a dropdown list that is dynamically populated as shown below: <form name="frmAccount" role="form" ng-submit="submit()"> <div ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Assign the value of ng-options based on the AJAX string value

There are two select menus on this page that receive data through AJAX JSON after the page loads. They are related to each other and structured like this: <select name="category" id="category" ng-model="category" ng-options=" ...

What sets class/instance methods apart from static methods when it comes to their functionality in applications?

As I develop APIs for my application, I've been curious about the difference between defining functionality methods like this: class Foo { static method1(req, res) {} static method2(req, res) {} } and class Foo { method1(req, res) {} method ...

Having trouble getting a value from a textbox to PHP using jQuery - can anyone lend a hand?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5b1.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script> <input type="text" id= ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

Creating seamless transitions between pages using hyperlinks

On the homepage, there are cards that list various policies with a "details" button above them. Clicking on this button should take me to the specific details page for that policy. However, each product can only have one type assigned to it. For instance: ...

What is the best way to transfer a content script variable to a background script in a Chrome Extension?

I am looking to transfer a variable named "website_hostname" from the content script to the background script. This variable holds the hostname of the website you are currently visiting. Content Script: var website_hostname = window.location.href; //Cod ...

Create a CSS menu that centers the links

Here is the CSS code I am using for my horizontal menu: nav { height: 40px; width: 100%; background: #F00; font-size: 11pt; font-family: Arial; font-weight: bold; position: relative; border-bottom: 2px solid # ...

Launching a modal using a method in Vue.js that includes constantly changing content

I am currently developing a feature in my VueJs component that involves opening a modal when a certain condition becomes true, and then retrieving data from a controller to display in the modal. After searching online, I have not been able to find clear i ...

JavaScript not functioning properly for the Sibice challenge on Kattis

Currently, I am in the process of learning JavaScript and a friend recommended trying out Kattis for solving tasks, even though it might not be ideal for JS. As part of this challenge called Sibice, the goal is to determine if matches will fit into a box. ...

The connection between the type of request and the corresponding response in an Ajax function

When using the following: xhr.setRequestHeader("Content-Type", "application/json"); Am I obligated to only receive a response in json format, or is it possible to receive an html response instead? If there is flexibility in receiving different formats, h ...

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

What could be the reason for the Azure server sending a Bad Request response?

My NodeJS application is currently hosted on Azure server and all APIs are functioning correctly, providing the expected responses. The issue arises when trying to run a GET API like the following: https://demoapp.azurewebsites.net/mymenu?userId=piyush.d ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

Contrast the Django variable against the Angular variable

I am encountering a challenge while working with Django backend and Angular frontend. The issue at hand is comparing a variable value from a Django view with another variable value from Angular. I have attempted the following simple approach, but it does ...