Can a child controller inherit a service "similar to" instance from its parent in any way?

Within my application, I utilize window instances that can encompass various views. Each window has the capability to contain multiple views as children elements.

function windowController($scope, WindowService) {
    WindowService.setWindowConfig($scope.window);
}

function viewController($scope, WindowService) {
    WindowService.updateDirtyState(true);
}

I am seeking a method to update the window from its associated view(s), while ensuring that only direct children have the ability to modify their parent windows. Since services are singletons, updating a view would impact all windows collectively.

Is there a solution to achieve this objective without requiring the use of an identifier for tracking purposes?

Answer №1

Services are like singletons, yet they have the capability to include constructors for objects beyond the one they return.

Here is an example outline of a service that makes use of this concept:

.factory('WindowService', function(){
  var service = {};

  var Window = function() {
    ...
  };

  Window.prototype.doSomething = function(){
    ...
  };

  var View = function(window) {
    this.window = window;
  };

  service.newWindow = function(){
    return new Window();
  }

  service.newView = function(){
    return new View(window);
  }

  return service;
});

If each ViewController has its individual parent WindowController, you can create them in this manner:

.controller('WindowController', function($scope, WindowService){
  $scope.window = WindowService.newWindow();
})
.controller('ViewController', function($scope, WindowService){
  $scope.view = WindowService.newView($scope.window);
})

You don't need to be concerned about IDs as the view objects will hold references to their window parents. In fact, if all ViewControllers have a WindowController parent, you can access that scope variable through prototypical inheritance by using $scope.window from the view directly instead of going through WindowService for window object access.

.controller('ViewController', function($scope, WindowService){
    $scope.view = WindowService.newView($scope.window);
    // no need for $scope.view.window.doSomething(), although it's possible
    $scope.window.doSomething();
})

Demo

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

Utilizing JavaScript for parallax horizontal scrolling (identifying optimal 50% of screen)

I have successfully implemented this code for vertical scrolling: $('.flapleftclass').css('top',(0+(scrolled*0.5))+'px'); This method works well because I am referencing to the top position. However, when it comes to horizon ...

Troubleshooting: Success with AJAX call in Chrome, but issues in IE

Having issues retrieving JSON data from a URL that displays the last 3 numbers of a webpage. The AJAX call functions correctly in Google Chrome but fails in Internet Explorer. I tried disabling caching using cache: false as suggested, but the problem persi ...

What are some effective techniques for training a model with complex, multidimensional data?

I am working with an array of input data consisting of 5 arrays of varying lengths. What is the correct method to create a tensor and structure for training purposes? [ [ [ [ 1, 2 ], [ 1, 2 ] ], [ [ 1, 2 ], [ 1, 2 ] ], [ [ 1, 2, 3, 4, 5 ], [ 1, 2, ...

Display data from two MySQL tables using AngularJS

[QUERY] I currently have 2 tables stored in a MySql database |Questions| ------------------------------ questionID|question|answer |Options| ------------------------------ Id|questionID|option|result My goal is to present this data in a specific format ...

In JavaScript, arrays are typically implemented using which data structure?

We are currently studying arrays in computer science and how they occupy a continuous range of memory space. In a traditional array, you are unable to insert or delete elements without shifting other elements around. For example: const arr = ['a&ap ...

Designing interactive elements that conceal individual paragraphs

I am working on a project that involves 3 buttons and 3 paragraphs. My goal is to create a JavaScript function that will hide all paragraphs except the one with the same letter as the button clicked. I want to achieve this by applying a CSS rule that adds ...

There seems to be a glitch with jQuery on my Angular.js website

I'm trying to implement Masonry.js on my website, and although I've managed to make it work, the solution feels like a messy workaround and I can't quite figure out why it's functioning (and not functioning well). The primary issues I& ...

Disable image loading for users who have javascript enabled

I find myself caught in a chicken-egg dilemma. The webpage I created contains numerous images that need to be loaded, and so I implemented a script that loads images as the user scrolls, similar to how Facebook or Google Images functions. When the user rea ...

Creating a dynamic SlickGrid spreadsheet - a step-by-step guide

My curiosity has been peaked by the SlickGrid plugin. It caught my attention because of the spreadsheet example, but unfortunately I couldn't get it to work. Is it truly feasible to create a spreadsheet where you can select a range of cells and copy/p ...

Update the functionality of the Rotate library event

I'm attempting to incorporate this code for my animation: link to my animation My issue arises when I try to trigger the picture animation upon clicking a button, here is the HTML snippet: <form> <input type="submit" value="change" onclick= ...

Utilize AdWords Scripts/Javascript to display array objects on separate rows within a spreadsheet

I am currently facing some difficulties in figuring out how to display objects from an Array on separate rows within a spreadsheet using Google AdWords. var SPREADSHEET_URL = "xxxx"; function main(){ var spreadsheet = SpreadsheetApp.openByUrl(SPREADSH ...

Is there a way to verify if a module is already present in Angular?

Currently I am verifying if angular is already aware of my module using the following code snippet: try { angular.module('myModule'); } catch (err) { angular.module('myModule', []); } Is there a more efficient way to accomplish th ...

Tips for keeping a video background stationary while allowing the text to move smoothly

When I added the video for the background, it only appears at the top of the page. However, I want it to be visible as the rest of the page is scrolled. <div class="hero"> <video autoplay loop muted plays-inline class="back-video&qu ...

Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project sto ...

Angular 1.5 - Component for fetching HTML content with dynamic data

Help needed with using Angular Component method. Developing a main html file with its main controller containing a JSON list of client data: clients: [{ "name": "John Jackson", "age": "21", "hair": "brown", }, { "name": "Janet Doe", ...

What is the best way to retrieve an AJAX response from a different domain?

Are there alternative methods to retrieve AJAX response and access data from a different domain without requiring changes on the server-side code? While YQL offers this feature, it comes with limitations such as a maximum of 1000 calls per hour for free u ...

Node.js TypeError: Unable to access property 'path' of an undefined object

In my Nodejs implementation, I am working on uploading various types of files (photos, mp3, pdf) to Amazon Web Services S3. Right now, I am focusing on uploading an mp3 file but keep encountering the error: "TypeError: Cannot read property 'path' ...

Creating an OAuth2 Request in Node.js

As I delve into constructing an OAuth2 request for the Box API, I find the example POST request provided a bit perplexing. This is mainly due to my recent foray into backend development. The example in question reads as follows: POST /token Content-Type: ...

display a message of achievement within the $http response

I am attempting to display a success message in the HTTP response for 3 seconds before redirecting the page. Here is the code snippet: <body ng-app='myApp' ng-controller='myCtrl'> <div class="col-lg-12 col-sm-12 col-xs-12 ...

Tips for showcasing several thumbnails simultaneously as you upload images on a webpage with HTML and JavaScript

function displayImage(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#selectedImage') .attr('src', e.target.result) }; reader.read ...