Is it possible for ng-change to invoke another controller?

Can someone help me with the following HTML code?

<div ng-controller="select">        
    <select ng-options="n for n in names" 
    ng-model="selected.item"
    ng-change="change()">
    </select>
    </div>
    <div ng-controller="graph">
    <input type="text" ng-model="mySelected.item">
    <canvas id="line" class="chart chart-line" chart-labels="gs" chart-data="ser">
    </canvas>
    </div>
    

I need the "change()" method in ng-option to trigger the "graph" controller when an option is selected. Essentially, when the option changes, I want the graph to update. Is there a way to achieve this? Please provide guidance.

Below is the code for my controllers:

app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService) {
    $scope.mySelected = myService.selected;
    console.log($scope.mySelected);
    //$http.get('/myapp/stocklist/'+ $scope.mySelected).
    $http.get('/myapp/stocklist/AMZN').
    success(function(data) {
    gs = [];
    ser = [];    
    for( var i=0; i<data.length; i++ ) {
        gs.push(data[i].name);
        ser.push(data[i].high);
    }
    $scope.gs=gs;    
    $scope.ser=[];
    $scope.ser.push(ser);
    });
    }]);

    app.controller('select', ['$scope', '$http', 'myService', function($scope,$http, myService) {
    $scope.selected = myService.selected;
    $http.get('/myapp/stocknames').
    success(function(data) {
        $scope.names=data;
        console.log($scope.names);          
    });
    }]);
    

Answer №1

To handle events in your graph controller, utilize the $on function like this:

    scope.$on('onServiceSelected', function (event, selectedService) {
           $scope.mySelected = selectedService;
    });

To broadcast events in your other controller, make use of the $broadcast function like so:

  $rootScope.$broadcast('onServiceSelected', $scope.serviceSelection);

Following these steps should guide you in the correct direction.

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

Ways to extract the id after clicking

In my code, I have a query called snapshot.forEach that functions similarly to a for loop in looping through all of my Firebase data and displaying it with a div tag containing a click event. When another user clicks on this div tag, the event will retriev ...

What causes the error "searchInput" to be undefined?

Currently, I am facing an issue while attempting to search for individuals stored in an array within the Redux store. Whenever I try to execute a search, an error is triggered with the following message: Cannot read property 'searchInput' of und ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

The visibility of the AmCharts' OLHC chart is compromised

Here is my unique StockGraph object: "stockGraphs": [ { "id": "g5", "title": "anotherText", "precision": 4, "openField": "open2", "closeField": "close2", "highField": "high2", "lowField": "low2", ...

Why are Actions and Reducers essential components in the Redux framework?

Despite my experience with Redux, I still struggle to grasp the purpose of actions and reducers. The documentation defines a reducer as (previousState, action) => newState, a concept also seen in React's useReducer. Having one function handle all ...

Exploring the World of Subclassing Arrays in JavaScript: Uncovering the TypeError of Array.prototype.toString's

Can JavaScript Arrays be subclassed and inherited from? I am interested in creating my own custom Array object that not only has all the features of a regular Array but also contains additional properties. My intention is to use myobj instanceof CustomArr ...

Transfer information via query or retrieve from storage in Vue

When considering sending a data variable to another component, is it more efficient to send it via query using a router or save the data in-store? Which method would be more optimal? router.replace({ name: 'routerName', query: { param ...

Firefox does not support the event

// This function makes rows draggable within a table by utilizing mouse events. // It handles the drag initiation, movement, and stopping of the drag operation. makeRowsDraggable: function() { var dragInitiated = false; var startPageX, startPageY ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

What is the best way to center align my horizontal subnav?

I am currently working on a horizontal navbar with horizontal submenus. One issue I am facing is getting the elements in mysubnav to align centrally instead of being pushed to the left all the time. If you need a visual representation of what I mean, plea ...

Can CSS actually generate accurate inches?

Can you accurately set the width of an element, like a div, in inches and expect it to maintain that width across different devices? Or will it simply scale at a ratio like 1in = 96px? Edit: Try using CSS to set an element's width in inches and then ...

Tips for inserting an element into every tier of a multi-layered array

I am faced with a challenging task of assigning an id field to objects within an array that has infinite levels. The rule is simple - for every level, the ID should correspond to the level number starting from 1. { "name": "Anything2&quo ...

Exporting an angular component as a module

I have successfully created a widget using Angular elements that works well in HTML. However, I am unsure of how to export it as a module for use in other Angular, React, Vue web applications. I want to be able to import import { acmaModule } from package- ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...

Utilize JQuery to implement fading effects for clicked elements in a webpage

I've been using a rollover JavaScript plugin to create smooth transitional effects when users hover over clickable page elements. Everything was going well until I decided to switch to making ajax calls instead of page loads for dynamic content. The p ...

Failure of Angular broadcast when used with a standalone service

I'm currently experimenting with the $rootScope.$broadcast method in AngularJS to trigger events within my services. To accomplish this, I have created a service specifically for event triggering and another service dedicated to catching these events. ...

Unable to display jQuery modal due to error "Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent."

Check out the JS Fiddle demo here. Here is the code in question: $('#infoTable').click(infoModal); function infoModal(){ var table = "THIS IS A TABLE"; $("#dialogContainer").dialog({ appendTo: "#msg-dialog", autoOpen: f ...

Disable toolbar focus in TinyMCE

Is there a method to prevent the appearance of the white square known as "Focus to toolbar" in TinyMCE? Clarification: Upon pressing Alt+F10 in TinyMCE, a white square is outlined around a button on the toolbar. This allows navigation among toolbar butto ...

Autonomous JQuery Modules

Is it possible to separate the functions in JQuery and use only the ones needed by splitting the file with PHP? By doing this, I aim to improve page speed, save bandwidth, and have more control over the functions used through the backend. Can the functio ...

Difficulty encountered when displaying JavaScript variable content within HTML in a React component

I'm currently exploring a backend administrative dashboard framework known as admin bro. My current project involves creating a tooltip component, and here is the code I have developed so far. class Textbox extends React.PureComponent { render() { ...