When the button in controller1 is clicked, the function in controller2 should be triggered

When a button is clicked in controller1, the function in controller2 should be triggered. I attempted to use a service, but it was not successful.

You can view the code on this plunkr.

Do you have any recommendations or suggestions?

Answer №1

Instead of relying on a service, opt for using broadcast to invoke a method from another controller.

.controller('ctrl', [
        '$scope', 'svc',
     function($scope, svc) {
         $scope.fun = function() {
             $scope.$emit('sampleEvent')
         }
     }
 ])
 .controller('ctrl1', [
       '$scope', 'svc', '$rootScope',
       function($scope, svc, $rootScope) {
            $rootScope.$on('sampleEvent', function(ev) {
                $scope.fun2()
            })
          $scope.fun2 = function() {
                alert("hi");
          }
      }
  ]);

Check out the Demo

Answer №2

If you are interested in implementing a service, you can achieve it by following this approach:

 (function() {
        angular.module('app', [])
            .service('svc', function() {
                var svc = {};

                svc.method = function() {
                   // You can call it here
                    svc.fun2();
                    //When the first controller is clicked, an alert box should open with the message "hi"

                }
                return svc;
            })
            .controller('ctrl', [
                '$scope', 'svc', function($scope, svc) {
                  $scope.fun = function(){
                    svc.method();
                  }
                }
            ])
            .controller('ctrl1', [
                '$scope', 'svc', function($scope, svc) {

                    $scope.fun2 = function(){
                      alert("hi");
                    }

                   // Inject your method to your service when it is defined
                    svc.fun2 = $scope.fun2;
                }
            ]); 
    })();

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

I find myself facing a roadblock in navigating Servlets and HTML

I'm currently immersed in a project aimed at launching an innovative online food ordering platform. To bring this vision to life, I've harnessed the power of HTML, CSS, and JavaScript for frontend development, Java (Servlets) for backend function ...

Launch a bootstrap modal from a different webpage

If you're looking to open multiple modals with different content displayed from HTML files, check out this example below: <div id="how-rtm-works" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" ...

Search for all documents in MongoDB and update all of them except for one

After performing a database lookup, I am receiving an array of objects as a result. [ { name: "test", services: { credentials: "123456" } }, { name: "test1", services: { credentials: "1 ...

Can animations be stacked in a queue while using velocity.js?

I'm currently tackling a project involving a push menu. When the content div slides over, the menu buttons come in with a slight animation as they appear on the screen. However, if the user rapidly opens and closes the menu multiple times, the items o ...

What is the best way to incorporate a third-party element into Vue using a script tag?

I am in the process of developing a website and I would like to include a widget that links to a podcast on BuzzSprout. Initially, I created the site using HTML to test out different designs, but now I am looking to transition it to VueJS. In my HTML vers ...

Repeated item discovered post-Ajax execution

I am currently working on implementing auto-complete functionality for form fields using AJAX and jQuery. Initially, I utilized Django and the views.py function below: def CreateWellMon(request): if request.method == 'POST': form = Su ...

Problem with deploying a Nextjs project on cPanel

I've been struggling to deploy a nextjs project on cPanel. The project consists of only one SSG page. I set the basePath in next.config.js to deploy the project, but I keep getting a 404 page not found error and the page keeps getting called in the ne ...

Tips for Seizing the "F2" key on ASP.NET Web Forms

I have a requirement in my web application where I need to open a new page when the user presses the F2 key. After some research, I discovered that this can be achieved with JavaScript. So, I wrote some code in JavaScript, but I encountered an issue - it ...

Creating an Angular 1.5 component that utilizes ng-model

Can ng-model be used with a component in Angular JS 1.5.6? I am trying to bind a scope variable to a component using ng-model. If you'd like to see my issue, check out my Plunker. Specifically, I want the component "my-input" to be bound to the userDa ...

Using Ajax, transmit an array from javascript to a php function

How can I send an array from JavaScript to PHP using AJAX? I'm not sure how to do this, especially when trying to send it to a PHP function like a controller class. Can someone please correct me if I'm wrong? Below is my current JavaScript code f ...

What could be the reason my ammap areas color isn't functioning properly?

1. Inquiry 2. Query Upon reviewing the console debug image, it seems that my color settings in dataProvider.areas are successful. However, the colorReal does not match the color, and the map displays the colorReal instead. How can I resolve this issu ...

Is there a way to implement Twitter Bootstrap Dropdowns with the first item acting as a toggle button?

Have you seen the Twitter Bootstrap Dropdowns Docs? They provide the syntax for creating a dropdown menu like this: <div class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a> <ul cla ...

Tutorial on using AngularJS with Apache server

Decided to take on the challenge of teaching myself AngularJS. I have a couple of outdated websites that could use some updating, so why not learn a new framework along the way! My current hosting doesn't support Node.js, so I just want to use Angular ...

Encountering difficulties in fetching data with formData in nextJS

Exploring the realm of NextJS and delving into server side actions. I'm facing a challenge with this specific request. import { revalidatePath } from "next/cache"; export async function submitIPCR(prevState: any, formData: FormData) { / ...

React and D3 Force Layout: uncharted territories for new links' positions

After carefully following the general update pattern for new React Props, I've noticed that D3 efficiently handles data calculation and rendering when receiving new props. This prevents React from having to render every tick. D3 functions seamlessly ...

Using React dangerouslySetInnerHTML with iframes

I am facing an issue with a component that displays a WordPress blog post. The post includes HTML markup as well as YouTube embeds using an iframe element. However, dangerouslySetInnerHTML is removing the iframes. How can I ensure this type of content is ...

Issue: The error message "undefined variable 'angular'" appears when attempting to access offline files stored on a network drive

I have successfully developed offline forms using angular js v1.6.4, angular-ui-bootstrap, and angular-ui-router without the need for server hosting. When the package is saved on local storage, it functions perfectly on both IE and Chrome browsers. Howeve ...

Adding a class to radio buttons and checkboxes in Angular when they are checked or selected without needing to trigger a change event

I am looking to implement ngClass based on whether an item is checked or not. Essentially, I want the user to visually see which items are selected through radio buttons or check-boxes by adding a class to them, allowing me to apply different CSS styles to ...

Guidelines for sending data as an array of objects in React

Just starting out with React and I have a question about handling multi select form data. When I select multiple options in my form, I want to send it as an array of objects instead of an array of arrays of objects. Can anyone help me achieve this? import ...

Creating various functions for Joomla's AJAX component development

My component is currently working smoothly with AJAX and mootools. The view.raw.php file contains only one function called display. I've been attempting to add other functions within the component that can be accessed through AJAX, but have been facin ...