Executing a function in a different AngularJS controller: a comprehensive guide

I've been scouring the internet for information on setting up two controllers in my AngularJS module, but all the answers I find seem to be outdated. I want to have one controller handling $http GET requests and another displaying success or error messages. Is it best to call a method from the second controller with the message to be displayed, or should I use a service or factory for this? Services sound promising, but I'm struggling to implement them in this context.

var module = angular.module('app', []);

module.controller('ApiController', ['$scope', '$http', function ($scope, $http) {
    $http.get('/api').
        success(function(data){
            // call AlertController('success')
        }).
        error(function(data){
            // call AlertController('failed')
        });
}]);

module.controller('AlertController', ['$scope', function ($scope) {
    $scope.message = {
        show_message: true,
        type: 'info',
        message: "Display message!"
    };
}]);

Alternatively, I might want to push incoming alerts onto a global object variable and remove them after display. Can anyone provide guidance on the best approach for this setup?

Answer №1

Alright, let's give this a shot - don't forget to take a look at Injecting $scope into an angular service function()

The Notification service:

module.service('NotificationService', function ($timeout) {
    var notificationQueue = [];
    var DISPLAY_DURATION = 5000; // each notification will be displayed for 5 seconds

    function startTimer() {
        $timeout(function() {
                // Remove the first notification in the queue
                notificationQueue.shift();
                // Start timer for next notification (if there is one)
                if (notificationQueue.length > 0) startTimer();
            }, DISPLAY_DURATION);
    }

    function add(notification) {
        notificationQueue.push(notification);
        // If this is the only notification in the queue you need to start the timer
        if (notificationQueue.length==0) startTimer();
    }

    function get() {
        if (notificationQueue.length==0) return "";
        else return notificationQueue[0];
    }

    return { add: add, get: get };
});

You can also make use of this Network service:

module.service('NetworkService', ['$http', function ($http) {
    return {
        fetch: function(url) {
            return $http.get(url);
        }
    };
}]);

Your Search handler:

module.controller('SearchHandler', ['$scope', 'NetworkService', 'NotificationService', function ($scope, network, notifications) {
    network.fetch('/yelp').
    success(function(data){
        notifications.add('success');
    }).
    error(function(data){
        notifications.add('failed');
    });
}]);

Your Popup controller:

module.controller('PopupController', ['$scope', 'NotificationService', function ($scope, notifications) {
    $scope.getNotification = function() { notifications.get(); }
}]);

So in your HTML you can include:

<div ng-controller="PopupController">
    <div>{{ getNotification() }}</div>
</div>

Answer №2

To create a factory, follow these steps:

    module.factory('appFactory', ['$window', '$http', '$q', function(win, $http, $q) {
    return{
        backendCall: function(){
            var deferred = $q.defer();
            $http.get('/api').
                success(function(data){
                    deferred.resolve(data);
                }).
                error(function(data){
                    deferred.resolve(status);
                });

            return deferred.promise;
        }
    }
  }]);

Next, set up your controller like this:

module.controller('DataController', ['$scope', 'appFactory', function ($scope, appService) {
    appFactory.backendCall().then(function(response){
            $scope.data = {
            display_data: true,
            type: 'success',
            message: "Display data here!"
        };  
    })

}]);

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

Inadequate completion of Object.create() method

Here's the code snippet: //Note: x is being pulled from an external source and contains certain values var x = [{ name: 'Michael Lovesllamas Lankford', created: 1338420951.11, laptop: 'pc', laptop_version: null, userid: &apos ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

Error: 'require' is undefined in react.production.min.js during production deployment

Greetings! I am encountering some difficulties while trying to build on production: the error "require is not defined" is being caused by react.production.min.js. Below are my webpack.config.js and package.json files: webpack.config.js const path = requi ...

Converting JSON data into a table using jQuery, with certain columns hidden from view

I am currently working on developing a mobile app using jQuery Mobile and JSON. I have encountered two separate questions: 1) I have a JSON data set which includes fields such as id, name, surname, point, and mail. In my table that lists this data, I init ...

Output the 'script' using the `document.write`

Revised inquiry I am endeavoring to construct two distinct HTML files: main.html and sufler.html. The concept is to manage the sufler.html page from main.html. To achieve this, I have devised a solution where I write the code for sufler.html as a string e ...

What is the best way to retrieve the transpiled string from babel-core?

I've been attempting to utilize babel with npm and it seems like the necessary package is babel-core. My goal is to provide it with a string of ES6 code and receive a transpiled code string in return. It sounds simple enough, but I'm having troub ...

When the promise is resolved, the members of the AngularJS controller are now

I'm experiencing some unexpected behavior in my controller when executing a certain method. The code snippet looks something like this: this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) => { this.StockItems = Stoc ...

What is the quickest way to accomplish this task?

Currently, I am in the process of constructing a dashboard using ASP.Net MVC, Angular.js, SQL Server, and Fusion charts. The data needed for charting is stored in a database and obtained through a stored procedure. My objective now is to convert the result ...

A single parallax transition designed exclusively for you

I am looking to add a unique parallax transition to my website, specifically one that features a nice scroll followed by a subtle bounce effect. For example, I want to incorporate an arrow that, when clicked, smoothly scrolls the user to the bottom of th ...

When scrolling, the header will automatically disappear until you reach the bottom. Once you start scrolling back up, the header

I couldn't quite figure out how to phrase this question, so I'm not sure if it's been asked before.. There is a header that disappears as you scroll down, like this: let prevScrollpos = window.pageYOffset; window.onscroll = function() { ...

Eliminate the classes that were inserted through Jquery

I'm currently working on an accordion and I've encountered an issue with jQuery adding classes that I don't want. How can I prevent jQuery from adding certain classes? The code below is what I have, but for some reason, jQuery keeps adding t ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

What could be the reason for AngularJS encoding the URLs for my POST parameters?

Take a look at our service's REST client: self.headers = { Accept: 'application/json', 'Content-Type': 'application/json' }; self.loginClient = $resource(self.baseUrl + '/users/login', { ...

Arrays Filtering without Containing Elements

Is there a utility function in Knockout to filter one array based on another array, or will I need to use JavaScript? First : var obj1 = [{ "visible": "true", "id": 1 }, { "visible": "true", "id": 2 }, { "visible": "true", "id": ...

The field "addWorkout" cannot be queried on the type "Mutation"

My journey with GraphQL has just begun, and after resolving a reference error in my previous question, I have encountered a new challenge. It appears that adding a workout is not working as expected, as the schema does not recognize it as a mutation field. ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Show the current phone number with the default flag instead of choosing the appropriate one using the initial country flag in intl-tel-input

Utilizing intl-tel-input to store a user's full international number in the database has been successful. However, when attempting to display the phone number, it correctly removes the country code but does not select the appropriate country flag; ins ...

Expanding a Node.js class to incorporate additional static class elements

I have a query where I believe that extending a class might be the solution, but I am not entirely sure. Here is the scenario... There is a class defined as follows: class Field { apiName; /** * Creates an instance of Field with the given par ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Trouble with formatting credit card numbers in Vue.js

My payment gateway component includes a feature where selecting credit card triggers the _formatCreditCard method to format the credit card number like this: 4444 2442 4342 3434 This is the function in question: _formatCreditCard: function() { var n ...