AngularJS: Triggering events in one controller to update data in another controller

I've tried several examples, but I'm not getting the expected results. In my project, I have two controllers - one for a dropdown and one for a table. When a user selects an item from the dropdown, a factory triggers a get request to update the table's data source. The get request successfully updates the IB variable, but the table source is not being updated as expected. Here's my HTML and JS code:

App.js: https://gist.github.com/fce53552ebc0ca8cdae68511a7cedc38 index.html: https://gist.github.com/3077b367bdf16e3e18e603fb93f37729

Any assistance on what might be going wrong would be greatly appreciated ;)

Answer №1

If you're looking to share data between controllers and only use one controller, I have a solution for you. Below is a functional demo that unfortunately won't work in a fiddle but works perfectly in the browser.

index.html

<!DOCTYPE html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    << script src = "ctrl.js" > < /script>
        < / head >
            <body>
                <div ng-app="app" ng-controller="moviesCtrl">
                    <h1>Movies By My Favorite Directors</h1>
                    <select ng-model="director">
                        <option ng-repeat="director in directors" value="{{ director.id }}">{{ director.name }}</option>
                    </select>
                    <table>
                        <tr>
                            <td>Movie Title</td>
                            <td>Lead Actor</td>
                        </tr>
                        <tr ng-repeat="film in movies[director].films">
                            <td>{{ film.title }}</td>
                            <td>{{ film.lead }}</td>
                        </tr>
                    </table>
                </div>
            </body>
</html>

ctrl.js

angular.module('app', []).controller('moviesCtrl', function($scope) {
$scope.directors = [
{
id: 0,
name: "Stanley Kubrick"
},
{
id: 1,
name: "Quentin Tarantino"
}
];
$scope.movies = [
{
directorId: 0,
films: [
{
title: "The Shining",
lead: "Jack Nicholson"
},
{
title: "A Clockwork Orange",
lead: "Malcolm McDowell"
},
{
title: "2001: A Space Odyssey",
lead: "Keir Dullea"
}
]
},
{
directorId: 1,
films: [
{
title: "Pulp Fiction",
lead: "John Travolta"
},
{
title: "Inglorious Buddies",
lead: "Brad Pitt"
},
{
title: "Django Unchained",
lead: "Jamie Foxx"
}
]
},
];
});

Note: The directorId field acts as a reference point for understanding which movies belong to which director but holds no significance within the code.

Answer №2

(Click here to view the plunkr example)

Delving into a common theme often encountered by beginners, I aim to provide a simplified response for your query. This is not an exhaustive tutorial but rather a concise summary to steer you in the right direction and encourage independent exploration. The solution primarily involves utilizing Angular directives, a robust pattern found in Angular 1.X (further enhanced in AJS 2.X). In this illustration, I introduce two directives - 'cf-get-data-button' and 'cf-show-data'. The former mimics a drop-down selection functionality (getData()), while the latter serves as a table where content gets dynamically updated (simulated as the latest UTC time). Additionally, I incorporate two crucial patterns: 1. a 'factory' pattern featuring a singleton service housing the ajax API, which is then 'injected' into the directives for accessibility; and 2. the utilization of async promises from ajax calls, concepts alluded to in your initial inquiry. Although I won't delve deep into these aspects here, exploring them further is recommended. Noteworthy is that in this scenario, the result of the simulated AJAX call ($timeout) becomes accessible only post the promise resolution.

Ultimately, you require an outer controller for your 'page', adhering to AJS' quasi MVC structure. However, each directive incorporates its own 'controller', aligning with the componentization and separation of concerns that you seek. The singleton service acts as the pivotal link for data management, facilitating data retrieval and consumption by both directives through injection. For instance, the simulated dropdown directive requests data, whereas the simulated table directive exhibits it (in UTC time). It's worth mentioning that directives can be customized in diverse ways, and the ones showcased here are relatively straightforward.

To commence, refer to the index.html snippet below (with the inclusion of 2 directives within the body and linked js scripts) and proceed from there. I've embedded comments within the js and html files for guidance. Don't hesitate to seek clarification if needed.

<!DOCTYPE html>
<html ng-app="Tutorial">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8e81889a838e9dc1859cafdec1dbc197">[email protected]</a>" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>

    <script src=app.js></script>  
    <script src=mock_ajax_service.js></script>
    <script src=getdatabuttondirective.js></script>  
    <script src=showdatadirective.js></script>
  </head>

  <body ng-controller="TutorialController">
    <p>One UI directive triggers update on another UI directive</p>

    <cf-get-data-button></cf-get-data-button>
    <br>
    <cf-show-data></cf-show-data>
  </body>

</html>

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

Why is DynamoDB still not deleting the item even though the promise returns successfully?

Using the DynamoDB DocumentClient, I attempted to delete items across multiple tables using Class: AWS.DynamoDB.DocumentClient A problem arose when I tried to delete items from multiple tables using promised.all(). The operation ran without deleting the i ...

Enhancing the appearance of list options in Autocomplete Material UI by utilizing the renderOption feature

I'm putting in a lot of effort to customize the option elements in the autocomplete list. My plan is to achieve this using the renderOptions prop, where I can create DOM elements and easily apply styles with sx or styled components. However, somethin ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

Click to reveal the hidden div located at the bottom of the webpage

I have created a simple webpage where all the content is visible without the need to scroll down. However, there is additional content at the bottom that I want to keep hidden until the user chooses to see it. The idea is to have a phrase at the bottom o ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

"Every time ajax is called, it will always generate

function lks() { var groupname = document.getElementById('groupname').value; $.ajax ({ url: 'verifyGroup.php?groupname='+groupname, type: 'get', ...

Click on a div in AngularJS to be directed to a specific URL

I'm currently working on developing an Angular mobile app and I want to be able to navigate to a specific URL, like www.google.com, when a particular div is clicked. Unfortunately, I'm still new to the world of Angular and struggling to achieve t ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

Tips for choosing elements based on a specific attribute (such as fill color) in D3.js using the SelectAll method

I have various sets of circles on a map - 10 red circles, 10 blue circles, and 10 green circles. Is there a way to use d3 selectAll or select to specifically choose only the red circles? Are there any alternative methods for achieving this? The color of ...

The AngularJS controller is not invoking the factory reference as expected

Having trouble getting a simple controller to work when adding a factory reference (homeFactory) to the constructor function. If the factory reference is removed, the controller functions properly. Interestingly, with the factory reference in place, the co ...

Employing the `instanceof` operator on instances generated by constructors from complex npm dependencies

Context: In one of my npm modules, I've implemented error handling code with a custom error type called CustomError: function CustomError () { /* ... */ } CustomError.prototype = Object.create(Error.prototype); CustomError.prototype.constructor = Cu ...

Utilizing winston to generate multiple log files with set maximum sizes and daily rotation

Currently, I am utilizing winston for logging with a maximum size and daily rotation. I am interested in having this functionality with one file per API endpoint to define multiple log files. Is there a way to achieve this? Displayed below is my winston ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

Transform the column's datetime into a date in the where condition when using sequelize

Hey there, I'm looking to convert a datetime column into just date format while running a query. Could someone assist me with creating a Sequelize query based on the example below? select * from ev_events where DATE(event_date) <= '2016-10- ...

What is the best way to bring a nested object to the top level without deleting the original top level

Imagine having the following dataset: data = [{ "_id" : "2fApaxgiPx38kpDLA", "profile" : { "name" : "Karina 1", "avatar" : "avatar1.jpg", "bio" ...

Loading `.obj` and `.mtl` files in THREE.js with accompanying PNG textures

I am facing an issue while attempting to load an mtl file with reference to png textures for my obj model. The error I am encountering is as follows: TypeError: manager.getHandler is not a function Below is the snippet of my three.js code: var loadOBJ = ...

Unusual perspective of JSON with ng-jsoneditor in AngularJS

Currently, I have integrated ng-jsoneditor into my AngularJS application to display and format JSON data. I found guidance on how to implement this from both here and here. Here is the HTML code snippet: <div ng-jsoneditor="onLoad" ng-model="vm. ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Use Yii2 to pass an ID when a button is clicked in order to render a partial using

On the index page, I display all the rows and some fields from my model. When a button is clicked, I want a modal to appear with all the data from the corresponding row. When the button is clicked, I need an ajax call to render a partial view. This will i ...