Invoke the initial AngularJs controller function from another controller

I have two AngularJs Controllers named "HomeController" and "VacancyController". In my HomeController, there is a method called getallData(). I am attempting to call the Homecontroller's getallData() function through the ng-change event of a dropdown. How can I achieve this considering that the on-change attribute of the dropdown is wrapped around "VacancyController"?

Here is the code snippet:

HTML

<div ng-controller="VacancyController">

<p>Select a Vacancy:</p>
<select ng-model="selectedVacancy" ng-options="x.name for x in vacancieslist" ng-change=""></select>
<h1>Your selected Vacancy Title is : {{selectedVacancy.name}}</h1>

HomeController

.controller('HomeController', function ($scope, angularSlideOutPanel, $http, $location, $window) {
getallData();

//******=========Get All Teachers=========******  
function getallData() {
    $http({
        method: 'GET',
        url: '/Home/GetAllData'
    }).then(function successCallback(response) {
        // callback will be executed asynchronously
        // upon receiving the response
        $scope.ListTeachers = response.data;
    }, function errorCallback(response) {
        // executed asynchronously if an error occurs
        // or server responds with an error status
        $scope.errors = [];
        $scope.message = 'Unexpected Error while saving data!!';
        console.log($scope.message);
    });
};

VacancyController

app.controller('VacancyController', ['$scope', 'VacancyService', function ($scope, VacancyService) {
$scope.GetVacancies = function () {
    $scope.vacancieslist = [];

    var getData = VacancyService.Vacancies();
    getData.then(function (ord) {
        angular.forEach(ord.data, function (val) {
            if ($.trim(val).length > 0) {
                var obj = new Object();
                obj.name = val.VacTitle;
                obj.id = val.VacNo;
                if (val.VacNo > 0) {
                    $scope.vacancieslist.push(obj);
                }
            }
        });
    }, function () {
        genericService.warningNotify("Error in getting List of Vacancies");
    });
}

$scope.GetVacancies();
}]);

Answer №1

There is a way for one controller to invoke another controller, as exemplified in this stack overflow thread (Can one controller call another?). You have the option to use emit or broadcast depending on their relationship. In your specific scenario, it would be more beneficial to place getAllData in a service. This service can then handle returning the result of getAllData. Within the service, you can either consistently return the result from an http call or cache the service by assigning it to a variable and returning it.

app.service('commonSvc', function() {
  var getAllData = function{... //your existing code here}
  return {
    getAllData:getAllData
  }
}

With commonSvc established, you can utilize and trigger this service whenever you need to utilize this function, similar to how you are implementing VacancyService. It's important to note that all services in Angular act as singletons. In vacancyController, you can then introduce a new function onChange which invokes commonSvc.getAllData.

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

What is the best way to store a username and password within a JavaScript object in ReactJS?

I am encountering an issue with obtaining the login credentials from the object. Although the code snippet below functions perfectly well with other forms. SignIn.js export default function SignIn(props) { const [state, setState] = useState({ userna ...

What is the best way to individually update fields using Prisma?

I am facing a challenge with updating fields individually for an object named Post. This object has three fields: title, content, and summary. Situation To save a post in the database, I can fill in just the title field initially and leave the other fiel ...

I am eager to develop a Loopback model tailored specifically for handling this JSON data

"US Virgin Islands": [ "Charlotte Amalie", "Christiansted", "Frederiksted", "Kingshill", "St John Island" ], I'm currently working with a JSON file that contains country names and corresponding cities. I want to store this data in my database using M ...

Is there a way for me to retrieve the information sent in a jQuery Ajax request?

I'm struggling to understand how to retrieve a value previously submitted to a PHP file using AJAX and jQuery. I'm still in the early stages of learning jQuery, so some concepts are challenging for me. Below is my jQuery code: $('#button2& ...

Simple way to automatically update Ionic List

I'm attempting to automatically refresh a list displayed using Ionic 1. I came across this codepen, but I'm having trouble grasping how it functions. https://codepen.io/calendee/pen/GkgsD?editors=1111 Below is the code for the list that I am ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...

Combining Angular variables within HTML tags: A Guide to AngularJS

As a newcomer to AngularJS, I am truly impressed by its capabilities. One thing I am eager to learn is how to include an AngularJS binding within an HTML attribute, while also adding another string to it. I often use unique names like "thisform" and "thisd ...

Using dojox gfx to enable a node to be draggable following retrieval of sgv data from a JSON source

I have a collection of shapes on a surface that I need to convert to JSON using the dojox.gfx.utils.toJson(surface) method. Once I have the JSON data, I then utilize dojox.gfx.utils.fromJson(surface, json) to append it back to the surface. However, I enco ...

Automatically update and reload Express.js routes without the need to manually restart the server

I experimented with using express-livereload, but I found that it only reloaded view files. Do you think I should explore other tools, or is there a way to configure express-livereload to monitor my index.js file which hosts the server? I've come ac ...

Working with Vuex: Simplifying state management by accessing multiple state objects with a single update mutation/action

I am facing a challenge with updating objects containing different strings using a single mutation and action in my project. Currently, I am attempting to extract a string from an input field's value and name, using the name as the object property to ...

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

Is there a way to incorporate arguments into my discord.js commands?

Hey there! I'm looking to enhance my Discord commands by adding arguments, such as !ban {username}. Any tips or guidance on the best approach for this would be amazing! const Bot = new Discord.Bot({ intents: ["GUILD_MESSAGES", "GUIL ...

What causes the sudden disappearance of the returned value from AJAX?

This piece of code is what runs on my server: modify_emp.php <?php echo $_POST[id]; ?> Below is the Javascript code in my HTML page: <script> $(document).ready(function () { var alreadyClicked = false; $('.element').h ...

Navigating through the Express Routing: Homepage and Error 404

I've been working on a Node application with Express, and currently have the following code snippet in my app: app.use('/', function(req, res) { res.render('index', {}); }); While this route is functioning properly ...

What is the best way to attach an onClick event to a PHP-generated link?

Currently, I'm attempting to implement an onclick event on a link within a PHP file. $body2 .= '<td class="sampling-list-td download-link">' . '<a ' . 'class="sampling-list-download" ' . 'href="#" ' . ...

Retrieving data from MySQL through AJAX does not yield any information

I have been following a tutorial from W3 schools on PHP and AJAX database. Majority of the content is working fine, however it seems that there is no data being retrieved from the MySQL database I created called "exercises" in the "exercisedb" database. B ...

JavaScript Subscribe / Unsubscribe Button

I am trying to create a simple JavaScript program that allows users to like and dislike content. However, I am new to JavaScript and finding it a bit challenging. Basically, when the user clicks on the Follow button, the "countF" variable should increase ...

Generate a distinct identifier for each computer and utilize it as a means of identification in instances where no user is currently logged

I am working on developing a web application that allows users to provide ratings for articles. The backend of the app is built using Django, while the frontend utilizes AngularJS. A rating consists of three properties: rater, value, and article. I want ...

The function `res.json()` is being called before the for loop has completed its execution

I am facing an issue with my application where the endpoint is supposed to fetch data from a MongoDb Database and return the results to the client. However, I am encountering a problem where an empty array is being sent before my for(){} loop finishes exec ...

The passport local strategy functions properly when tested with Postman, but encounters a "missing credentials" error when used with axios

I am currently working on creating a login system using passport and a local strategy. Strangely, when I attempt to send the request through axios it doesn't seem to work, although it functions properly with Postman. When using axios, I receive an er ...