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

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Using Javascript Timers in an ASP.NET AJAX application with the pageLoad() function

function initiatePageLoad() { clearTimeout("MessagesTimer"); clearTimeout("NotificationsTimer"); var MessagesTimer = setTimeout("CheckMessages()", 15000); var NotificationsTimer = setTimeout("CheckNotifications()", 15000); } I've be ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

Having trouble with React's conditional rendering not working as expected?

I am currently working on updating the contents of my Navbar and Router by using useContext and conditional rendering techniques. Here is a snippet from my App.js: import "./App.css"; import axios from "axios"; import { AuthContextProv ...

In React Native, I must include individual radio buttons for each item retrieved from the API

When I select a radio button on mobile, all radio buttons get selected instead of just the one clicked. Here is the current behavior: https://i.stack.imgur.com/qRJqV.jpg The expected behavior is to have only the clicked radio button selected, like in thi ...

Troubleshooting tip for React JS: encountered an unexpected object error when trying to import components

I've been working on building a react app with Create React App, and everything was going smoothly until I encountered a frustrating error message: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

The parsing of source maps fails due to issues with the .htaccess file

After analyzing the web page, I found that the .htaccess file contains the following code: RewriteEngine On RewriteBase / Options -MultiViews DirectorySlash Off # skip POST requests RewriteCond %{REQUEST_METHOD} POST RewriteRule ^ - [L] RewriteCond %{R ...

What is the best way to convert API data into a currency format?

Hello, I need assistance with formatting data retrieved from an API into a currency format. The code below successfully retrieves the data but lacks formatting. For instance, if the data displays as 100000000, I would like it to be formatted as IDR100.000. ...

The Jssor bullet navigator is not visible on the webpage

Currently, I am working on implementing a full-width slider with arrow navigators, bullet navigators, and captions using the Jssor plugin. Rather than copying and pasting example code, I decided to tackle this project independently with just a little guida ...

The issue with GatsbyJS and Contentful: encountering undefined data

Within the layout folder of my project, I have a Header component that includes a query to fetch some data. However, when I attempt to log this.props.data in the console, all I get is 'undefined'. Could someone please point out where I might be m ...

The internal cjs loader in node threw an error at line 1078

I'm encountering an error on Windows 10 when running the npm command: node:internal/modules/cjs/loader:1063 throw err; ^ Error: Cannot find module 'D:\mobile-version portfolio\ at Module._resolveFilename (node:internal/modules/cjs/load ...

Monitor the fullscreenChange event with angularJs

Utilizing a button to activate fullscreen mode for a DOM element using the fullscreen API is functioning correctly. The challenge arises when exiting fullscreen mode, requiring the listening for the fullscreen change event in order to resize the DOM elemen ...

React search filter feature with dropdown selection

After successfully implementing a search filter in my React app, I encountered an issue when trying to incorporate a select tag to change the search filter criteria. class BookList extends Component { state = { search: '', selectedValue: ' ...

Tips for concealing the Google Chrome status bar from appearing on a webpage

I have been intrigued by the rise of Progressive Web Apps (PWAs) and I am eager to dive into understanding them better. One common feature I have noticed in PWAs is the ability to hide the browser chrome, including the URL bar, back button, search fields, ...

Sending a sound recording to the express js server with the help of multer

I'm currently working on a project where I need to record audio and save it in my local directory (uploads folder) using express js and multer. The recording part is working fine with mic-recorder-to-mp3, but I'm facing an issue with saving the r ...

When I attempt to click on the Cancel button, the database row remains undeleted

After a user clicks on the "Cancel" button, I want to reset the source and remove the iframe to prevent the file from being uploaded to the server. This function is currently working as intended. However, I am facing an issue where even after clicking on ...

Guide on inserting HTML text box form input into Express route parameter

I'm currently working on implementing a feature that allows users to search through my mongo database using an endpoint structured like this: app.get('/search/:input', function(req, res){ console.log(`get request to: /members/${req.params ...

Discovering the selected href URL using JQuery or JavaScript

How can I detect the clicked href URL using JQuery when no ID is being used? For example, if I have a list of links where some redirect to new pages and others call javascript functions to expand a div. What approach should be taken in JQuery/Javascript ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

I am struggling to add a list from these nested functions in Express, but for some reason, the items are not being properly

I am currently working with three nested functions and facing an issue where the last function is not returning the desired list of items. Interestingly, when I log the results of the last function within the loop, I can see the URLs that I need. However, ...