What is the best approach to execute a function in two distinct controllers using angularjs?

My setup includes two distinct angularjs controllers: HomeController and SearchController.

Within HomeController, there is a function named Search().

I am seeking guidance on how to execute the search function from SearchController.

Answer №1

Implement the 'find' method within a factory, then inject this factory into multiple controllers to utilize the 'find' method across them.

Example:

app.controller('MainController', function(searchFactory){
   //Invoke factory method
   //searchFactory.find();
});

app.controller('SecondaryController ', function(searchFactory){
   //Invoke factory method
   //searchFactory.find();
});

app.factory('searchFacotry', function(){
  return{
    find: function(query){
      alert('hello world');
    };
  };
});

Answer №2

Check out this Plunker that I created to demonstrate the concept discussed above. The code snippet below shows the implementation in the app.js file, utilizing a factory declaration. Alternatively, if you only need a function to store and return data, consider using the $rootScope service from Angular as it is globally accessible. Services are preferable when they perform specific operations. For further insights on services versus rootScope, refer to this informative article.


app.controller('DashboardCtrl', function($scope, dataService) {
    $scope.displayData = function() {
        dataService.getData();
    }
});

app.controller('ProfileCtrl', function($scope, dataService) {
    $scope.retrieveData = function() {
        dataService.getData();
    }
});

app.factory('dataService', function(){
    function getData(){
        alert('Hello Universe');
    }
    
    var service = {getData: getData};
    return service;
});

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 retrieve information from a mongoDB database and showcase it on a react user interface?

I'm in the process of learning MERN and seeking guidance on how to fetch all the data from a specific collection. I have successfully built the backend code, which works well when tested with Postman. However, I am struggling to retrieve and display t ...

once a value is assigned to the variable "NaN," it remains constant and does not alter

What is the reason for not getting an assigned value in the line val3.value = parseInt(val1.value + val2.value);? Is it because the specified value "NaN" cannot be parsed, or is it out of range? var val1 = parseInt(document.getElementById("num1")); var ...

Establishing the default tab in JavaScript

Here's the JavaScript code snippet I have: jQuery(document).ready(function($) { // filtering subcategories var theFilter = $(".filter"); var containerFrame = $(theFilter).closest(".container-frame") var filterHeight = $(".filter").children("li") ...

Retrieve a result from this promise

I have encountered a problem that my classmates at school cannot solve. I have a piece of code that is working fine and sending the table of objects potentials to the client side. However, I now realize that I also need another object called userData. I ...

Simpler and more sustainable methods for embedding HTML elements using a configuration file

Currently, I am devoting my time to a toy project that heavily relies on JavaScript. A key component of this project is a JSON file that contains configurations and input descriptions, along with range values and options. This JSON file enables me to easil ...

Debounce on React Component

Attempting to add a delay to a react component with an input field that updates when changed Below is the method used for onChange: handleOrderQtyKeyPress (e) { var regex = /[^0-9]/ if (e.key.match(regex)) { e.preventDefault(); } ...

Is it possible to validate input only during insertion in Objectionjs without validation during updates?

const BaseModel = require("./base_model.js"); class CustomerModel extends BaseModel { static get tableName() { return "customers"; } static get jsonSchema() { return { type: "object", required: ['na ...

Issue with Gulpfile.js - cannot locate module

Hey everyone, I'm new to posting so please bear with me... I've been following a tutorial by Kevin Powell on setting up gulp to automate SCSS compiling and more. You can check out the tutorial here. I thought I followed all the instructions cor ...

Looping through ng-repeat within ng-repeat-start is a great way

An individual new to angularJS encountered an issue where the page intermittently breaks and displays angularjs code in the browser when using ng-repeat inside ng-repeat-start. <table> <tr ng-repeat-start="(key, value) in obj">{{key}}</t ...

Learn the process of adding values to HTML forms within ExpressJS

I am facing a challenge in injecting Javascript variable values into HTML forms on an Expression JS server. I am unsure about how to solve this issue. All I want to do is insert the values of x, y, and res into the forms with the IDs 'firstvalue&apos ...

Using jQuery to Capture Datepicker Input and Assigning to PHP Variable

I need help figuring out how to save a jQuery datepicker value in a php date formatted variable. My goal is to have: input field named "reviewdate" = 03/02/2015 input field named "reviewmonth" = 3 Both values should be stored in a mysql database. I am ...

JavaScript timer that activates only on the initial occurrence

Is it possible to automatically execute a function 3 seconds after pushing a button? The code snippet below should do the job: button.onclick = setTimeout(yup,3000); The function being called is named yup. After the initial button click, the function tri ...

Retrieving the height of the HTML body once all data has finished loading in AngularJS

Trying to determine the height of the HTML document (body) after loading content from a service using AngularJS. /* DISPLAY RECENT POSTS */ app.controller('RecentPostsController', function ($scope, $http) { $http.get("/site/recentpostsjs ...

Automatic closing of multile- vel dropdowns in Bootstrap is not enabled by default

I have successfully implemented bootstrap multilevel dropdowns. However, I am facing an issue where only one child is displayed at a time. <div class="container"> <div class="dropdown"> <button class="btn btn-default dropdown-to ...

The backdrop of a Bootstrap $modal window removes any elements from the screen

My app is experiencing an issue that I am having trouble replicating in a simplified version. When navigating through my SPA, clicking on an element opens a modal window using bootstrap $modal. However, when the modal window appears, everything else from t ...

Is there a way to turn off internal redirect handling in NextJS and have the browser take care of it instead?

I am currently creating a sample example to demonstrate basic cookie and magic link authentication. The process typically unfolds as follows: If the authorization token cookie is not present in the request when accessing protected paths, within the getSe ...

Utilize various designs on Bootstrap cards

In my Angular 9 project, I'm utilizing Bootstrap 4 cards with NGFOR to dynamically display elements fetched from the database. I have an array containing different styles for the card border, and I want each card to apply a random style from this arr ...

Proper utilization of the $pristine property in an AngularJS form

Upon the initial form load, I noticed that the $pristine property is consistently false. I believed that the $pristine property should remain true until the user interacts with the form in some way to change the model. Are there any other factors that co ...

How should I manage objects that are passed by reference in the context of functional programming?

Lately, I have been experimenting with some code in an attempt to delve deeper into functional programming. However, I seem to have hit a snag. I am struggling with handling an object. My goal is to add key-value pairs to an object without reassigning it, ...

Is it possible for PHP and AJAX to have a message box that scrolls along with the

I'm encountering an issue with my PHP message system where the div automatically scrolls to the bottom every 200ms to display new messages. However, users are unable to scroll up as they keep getting forced to the bottom repeatedly. What method can I ...