"Nested AngularJS controllers: a deep dive into the world

Recently, I've been delving into the world of AngularJS and I can't shake the feeling that my approach to the paradigm might be a bit off.

I have a controller for managing panes (linked to an ng-repeat) which tracks which panes the user has open. Each pane is supposed to contain data, leading me to think that most of them will need their own separate controllers inside.

I came across this answer on Stack Overflow (similar scenario), where the suggestion was to refactor the "popup" controller into a service.

The pane controller:

app.controller('PaneCtrl', function ($scope, PaneService){
    var updatePanes = function(panes){
        $scope.panes = panes;
    }

    // subscribes this controller to the Pane Service
    PaneService.registerObserverCallback(updatePanes)
});

Service

app.factory('PaneService', function(){
    var observerCallbacks=[]
    var panes = []

    var notifyObservers = function(){
        angular.forEach(observerCallbacks, function(callback){
            callback(panes);
        });
    }

    return {
        createRootPane: function(title, meta, data){
            // implementation details here
        },

        toggleSearchPane: function(){
            // implementation details here
            notifyObservers();
        },

        registerObserverCallback: function(callback){
            observerCallbacks.push(callback);
        }
    }
});

I'm seeking advice on what the best practice would be in this scenario, and if indeed the recommended practice is to "rewrite this as only a service", how should that service be structured?

Answer №1

My recommendation would be to rephrase this into a directive and establish the model <=> view connection within the directive's controllers.

For an example, you can refer to the tab demonstration in the Angular documentation on directives found in the Angular Documentation under Creating Directives that Communicate. If you need to fetch data from an external source to populate scope or utilize caching, consider using a factory.

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

"Unsuccessful Grails GSP Ajax Call: OnSuccess Function Fails to Trigger

Within my Grails .gsp file, I am executing an ajax call: $.ajax({ async: false, url: '<g:createLink controller="mycontroller" action="myaction"/>', data: params, dataType: 'json', contentType: 'application/json; ch ...

Prevent accordion expansion triggered by the More button click

When the More button is clicked, it should NOT expand and collapse. https://i.sstatic.net/toV1b.gif If the accordion initial state is open, it must stay open even if button is clicked, if initial state is collapsed then after the more button the accordio ...

Develop a Windows 8.1 Store App using VS Cordova and AngularJS

After downloading and implementing the two AngularJS demos from the links below, The demos functioned properly on WP8 and Android devices. However, upon deployment to Windows 8 Store App, the input box malfunctioned in both cases. I attempted using both ...

JavaScript AJAX function is returning an undefined value rather than a boolean true or false

My AJAX call function in jQuery has a complete section with the following code: complete: function(XMLHttpRequest, textStatus) { if(textStatus == "success") { return(true); } else { return(false); } } However, when ...

Change element's parent property's child property into an array form

Question 1: Do you believe that element.property is the same as element[property]? If your answer to question 1 is affirmative, then move on to Question 2: Can you convert element.parentProperty.childProperty into array syntax as explained in question ...

Guide to incorporating rate-limiter-flexible into your current node.js express configuration

I am currently using node.js, passport, and JWT bearer token for securing my routes. However, I have yet to implement rate limiting and IP/user blocking for too many false login attempts. What is the recommended approach to integrate this into my existing ...

Adjusting the speed of Flexslider with mousewheel control

I am looking to implement flexslider with mousewheel functionality. Here is an example of how I want it to work: $('#slider').flexslider({ animation: "slide", mousewheel: true, direction: "vertical", ...

Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event dat ...

URL JSON data will not display markers

I am currently working on a map that fetches data from the police.uk API by allowing users to drag and drop a dot on the map to display crimes within a 1-mile radius. However, I'm facing an issue when trying to implement geocoding functionality by tak ...

Tips for optimizing caching of API responses and assets using service workers in Vue CLI 3

import { register } from 'register-service-worker' import pwa from '@vue/cli-plugin-pwa' if (process.env.NODE_ENV === 'development') { // if (process.env.NODE_ENV === 'production') { console.log(pwa) register(`${pro ...

Is there a way to iterate through objects and add new properties to them?

I am trying to achieve the following object: let newPost = { title: "Post 1", Content: "New content" } with the code below: let newPost = {}; let postData = $(".post-data").each (function(index) { newPost.title = $ ...

After logging in successfully, the React app needs a hard refresh to update the

I'm encountering a debugging challenge and would appreciate any assistance from the community. I've been working on my first React app and successfully implemented a Login feature, but after a user logs in, they have to hard refresh their browser ...

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

Cross-Origin Resource Sharing (CORS) Issue: How Angular.JS, Node.JS, and

Encountering problems retrieving data from a http post request to my API. Seeing the following error message: XMLHttpRequest cannot load (URL to API here). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

Access the JavaScript variable in a webview and store it in an Android variable

I have been attempting to retrieve a variable from a webview, but I am only able to make modifications like this: browser.loadUrl("javascript:var x = document.getElementById('login').value = 'something';"); However, I need to be able ...

BreezeJS model, Knockout integration, empty relationships

I am facing an issue where, when using breeze manager.saveChanges(), only the navigation properties are not sent to the server. The rest of the data is being transferred properly. I am relatively new to Breezejs and hoping someone experienced can assist me ...

Ext JS - A grid cell containing varying values, accompanied by a selection of combo boxes

I'm currently implementing the Ext JS Grid component and have a list of fields with their respective data types: ID (int) Name (string) Foods (List<string>) Each user can have multiple foods, selected from a Food DataStore. Displaying this in ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Issue with Angular UI-Grid: Tooltip not appearing

I'm having trouble implementing a filter on ui-grid cells while also adding a tooltip. The filter works fine, but the tooltip does not display unless I remove the filter. cellFilter: 'number: 2', cellTooltip: 'Custom tooltip - maybe som ...