one component shares information with another component through a single controller

My goal is for the component dbServerTable to provide data to dbServerInfoSidebar whenever a list item from dbServerTable's template is clicked. However, I am experiencing an issue where no data is being displayed in dbServerInfoSidebar.

(function(angular) {
    'use strict';
    angular.module('SplashDamageApp').component('dbServerTable', {
        templateUrl: 'dbServerTable.html',
        controller: 'AppCtrl',
    });
})(window.angular);

(function(angular) {
    'use strict';
    angular.module('SplashDamageApp').component('dbServerInfoSidebar', {
        templateUrl: 'dbServerInfoSidebar.html',
        controller: 'AppCtrl',
    });
})(window.angular);

It is worth noting that both components share the same controller.

//AppCtrl
$scope.selectServer = function(item)
{
    $scope.selectedItem = item;
}

// dbServerTable.html
<tr data-ng-repeat="item in items | filter:search | orderBy:'name'"  data-ng-click="selectServer(item)">
    <td>{{item.display_name}}</td>
</tr>

//dbServerInfoSidebar.html
<h1>{{selectedItem}}</h1>

Upon clicking a list item, the selectServer() function successfully captures the item, but it fails to pass it to the dbServerInfoSidebar.html.

I would greatly appreciate any guidance on how to establish this data connection. Feel free to provide code examples as well :)

Answer №1

When creating two components, it is important to note that they will not automatically share the same instance of the AppCtrl controller. Each component will have its own instance of the controller. Therefore, modifying $scope.selectedItem in one component will not affect the value of $scope.selectedItem in the other component.

To achieve the desired outcome, you can create a service that will be shared between the controllers. By injecting this service into both controllers, you can set and access the selectedItem consistently across components. Services are designed as singletons by default, ensuring that both controllers receive the same instance of the service. This means that any changes made to selectedItem in the service will be reflected in all components.

Here is an example implementation:

// Shared service
(function(angular) {
        'use strict';
        angular.module('UniqueApp').service('DbServerService', function() {
            this.selectedItem  = undefined;

        });
})(window.angular);

// AppCtrl
(function(angular) {
        'use strict';
        angular.module('UniqueApp').controller('AppCtrl', ['$scope', 'DbServerService', function($scope, DbServerService) {
            $scope.getSelectedItem = function() {
                return DbServerService.selectedItem;
            }

            $scope.setSelectedItem = function(item) {
                DbServerService.selectedItem = item;
            }

        });
}])(window.angular);


// dbServerTable.html
<tr data-ng-repeat="item in items | filter:search | orderBy:'name'"  data-ng-click="setSelectedItem(item)">
    <td>{{item.display_name}}</td>
</tr>

//dbServerInfoSidebar.html
<h1>{{getSelectedItem()}}</h1>

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

How can I make the columns in Next.js / Tailwind expand horizontally first instead of vertically?

Recently, I decided to customize the Next.js Image Gallery starter for some hands-on experience in full stack development with Next.js. My goal was to create a chronological photo gallery of a recent trip, but encountered an issue where the responsive colu ...

Tips for repeatedly clicking a button over 50 times using Protractor

Is it possible to click the same button more than 50 times using a loop statement in Protractor? And will Protractor allow this action? Below is my locator : var nudge= element(by.xpath("//a[@class='isd-flat-icons fi-down']")); nudge.click(); ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

Structural engineering for massive webpage

Currently I am in the process of building a large page using AngularJS. As I plan out the architecture for this page, I am debating which approach would be most effective. The page consists of 3 distinct blocks with various functionalities, but the prima ...

React checkbox displaying incorrect render

I'm currently working on developing a React component that acts as a tile representation. This particular component consists of a div containing a label and a checkbox. The issue I'm facing is that I can click anywhere on the component to trigg ...

Breaking down the text field into two distinct fields

I have successfully modified the code below to meet a new requirement. The current functionality involves splitting the Price field into Pounds and Pence based on the index of the . symbol. However, I now need to extend this functionality to split a Name ...

How can I show the text name as a selection in the React Material UI Autocomplete component while sending the ID as the value?

Material UI Autocomplete component functions properly, but I am interested in extracting object.id as the value for the onSelect event (rather than object.name). Essentially, I want to display the object.name as the select item label, while retrieving obje ...

HTML / CSS / JavaScript Integrated Development Environment with Real-time Preview Window

As I've been exploring different options, I've noticed a small but impactful nuance. When working with jQuery or other UI tools, I really enjoy being able to see my changes instantly. While Adobe Dreamweaver's live view port offers this func ...

What is the method to track the number of tspan elements within each span element?

How can I use jQuery to count the tspan elements inside multiple span elements within svg text? var count_tspan = jQuery('span text').children().length; // 4 console.log(count_tspan); <div class="content-inner"> <span id="item-0" cl ...

Issues occurring with PhoneGap preventing the execution of AngularJS code

I've recently delved into learning AngularJS with PhoneGap and I have a basic HTML code along with some AngularJS snippets. While everything runs smoothly in the browser, only the HTML portion seems to work when I attempt to run it on my Android phone ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

Refreshing the view following a model update within an AJAX call in the Backbone framework

I'm struggling with my code as I can't seem to get my view to update after a model change. var ResultLoanView = Backbone.View.extend({ id:"result", initialize: function(){ this.render(); this.on('submissionMa ...

Is it possible to utilize the onClick event while preserving the use of "this" within the function it triggers?

There is a project with specific needs that require implementation. The task involves adding points to the total score when a button is clicked, without making any changes to the provided HTML code. This requires writing unobtrusive JavaScript code by atta ...

Retrieve the currently logged-in user whenever the component is rendered using React's Context API

For my small React project, I am utilizing ContextAPI. Whenever I hit the /login endpoint, I store the user's token using an HttpOnly Cookie. Below is the code for UserContext.js, which encapsulates all components (children) within App.js import axio ...

"Error: The req.body object in Express.js is not defined

edit:hey everyone, I'm completely new to this. Here's the html form that I used. Should I add anything else to this question? <form action="/pesquisar" method="post"> <input type="text" id="cO" ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...

Is Axios phasing out support for simultaneous requests?

According to the current axios documentation, there is a section that is not very well formatted: Concurrency (Deprecated) It is advised to use Promise.all instead of the functions below. These are helper functions for managing concurrent requests. axio ...

Customize the AngularJS ng-grid filter to format the filter text

Currently, I am working with ng-grid in AngularJS (v2.0.8) and I am interested in exploring the syntax for the filterText field within the API. Specifically, I am looking to understand how to filter data based on certain columns and how to filter multiple ...

Looking for a way to dynamically adjust the height based on window resizing

I am trying to figure out how to adjust the height of a scrollable grid dynamically. I came across a solution on this website However, the provided solution is not suitable for me as it has: styles: [` html, body, my-app { height: 100%; } '] ...

Leverage OpenID Connect in Azure Active Directory with authentication code flow

Currently, I am developing an authentication system for a NodeJS and Express web application that requires users to be directed to Microsoft SSO. To achieve this, I am utilizing passport-azure-ad and OpenID Connect. My main query is - Is it mandatory to ...