How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to call functions within the same ng-app, but what I really need is to call a function from another ng-app.

Below is my code. Any help would be greatly appreciated.

<body>
<div id="UserControllerDiv" ng-app="UserTableApp" ng-controller="UsersController" class="form-group">
    <br /><br />
    <p>Search : <input type="text" ng-model="search" /></p>
    <table class="table table-hover">
        <thead>
            <tr>
                <th>First Name</th>
                <th>Middle Name</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="u in users | filter:search">
                <td>{{ u.FirstName }} </td>
                <td>{{ u.MiddleName }} </td>
            </tr>
        </tbody>
    </table>
</div>
<br />
<div id="UserFormDiv" ng-app="UserFormApp" ng-controller="UserFormCtr" class="form-group">
    <table class="form-group">
        <tr>
            <td>First Name</td>
            <td> : </td>
            <td><input type="text" ng-model="FirstName" class="" /> </td>
        </tr>
        <tr>
            <td>Middle Name</td>
            <td> : </td>
            <td><input type="text" ng-model="MiddleName" /> </td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td>
                <button ng-click="submit()">Save</button>
            </td>
        </tr>
    </table>
</div>
<script>
    var userTableApp = angular.module("UserTableApp", []);
    userTableApp.controller("UsersController",
        function UsersController($scope, $http) {
            $http.get("http://localhost:10160/UserService/Users")
            .success(function (response) { $scope.users = response; });
        });
    var userFormApp = angular.module("UserFormApp", []);
    userFormApp.controller("UserFormCtr",
        function UserFormCtr($scope, $http) {
            $scope.submit = function () {
                var dataObj = {
                    FirstName: $scope.FirstName,
                    MiddleName: $scope.MiddleName
                };
                var res = $http.post("http://localhost:10160/UserService/AddUser", dataObj);
                res.success(function (data, status, headers, config) {

                    /****** Here I want to call the UsersController function of UserTableApp  ************/
                    /* I tried the code below but it did not work */
                    var scope = angular.element(document.getElementById("UserControllerDiv")).scope();
                    scope.$apply(function () { scope.UsersController($scope, $http); });
                    /*************************************************************************************/

                });
                res.error(function (data, status, headers, config) {
                    alert("failure message: " + JSON.stringify({ data: data }));
                });
            }
        });
    angular.bootstrap(document.getElementById("UserFormDiv"), ['UserFormApp']);
</script>

Any assistance provided would be highly valued...

Answer №1

Learn how to execute a function from another controller application with this simple guide.

 var scope = angular.element(document.getElementById("AnotherControllerDiv")).scope();
                scope.executeFunction();

Watch as the flow seamlessly transitions to the specified function. To confirm, verify that your method is present in the scope object within the console. You're on the right track!

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

Is it possible to modify state prior to the link being activated in react-router-dom?

I need to gather user information before the link works, but I'm not sure how to do that. The issue is that when I click on the link, the component it's linking to gets activated first without receiving the necessary info. const [userId, setUse ...

Does catching errors cause the for loop to stop in JavaScript?

for (let index = 0, total = IDs.length; index < total; index++) { item = IDs[index]; hasError = false; try{ let id = db.getSiblingDB("door").jhi_user.findOne({"_id" : item}); } catch (error){ failedIDs.push(item); ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...

Executing function with ng-click in AngularJS only on the second click of the button

Currently, I am studying AngularJS and working on an exercise that involves using the ng-click function. Strangely, I am only able to view the result after clicking upload for the second time. I am trying to display my json content but it's not workin ...

Executing Code from Tab only upon tab activation

I have multiple tabs on my page, and I want to have one tab with a widget that only loads when the user clicks on it, instead of loading along with all other tabs when the page loads. <div class="tabbable tabbable-custom"> <ul class="nav nav-t ...

Changing the MIME type of a JavaScript file in a Jade/Pug environment to text/html

Hi there, I've been experimenting with jade/pug to get my node.js backend to render the front-end pages. However, I'm facing some issues when trying to include JavaScript for certain functionalities. Whenever I try to load it, I encounter this er ...

Unveiling Three.js: Exploring the Unique One-Sided Surface

Here is the three.js code: <script type="text/javascript"> init(); animate(); // FUNCTIONS function init() { // SCENE scene = new THREE.Scene(); // CAMERA var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight; var VIEW_A ...

How can I customize a currency directive in AngularJS using filters?

My goal is to enhance user experience by allowing input in custom currency values like '1.5M' instead of 1500000, and '1B' instead of 1000000000 on an input form dealing with large numbers. To achieve this, I've created a FormatSer ...

Exploring nested selection with css and utilizing the ::focus pseudo class

Is it possible, using CSS, to target the helpTextInvalid class when the div element with the selectize-input class is in focus? <html> <head> <body> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/lib ...

In Cypress, I am trying to specifically choose only numerical values from a dropdown menu. However, the list contains a mix of alphanumeric and numeric values

Looking to streamline: This is my code: cy.get('[role=presentation]') cy.get('[role=row]').find('td') .get('[role=gridcell]').eq(9).click().wait(2000) cy.get('[role=listbox]').get('[role=option]& ...

Tips for using the POST method to open an external URL in IONIC - what you need to know

I have a CodeIgniter Controller set up on the server to create an Excel file, and it's working well on the web using the submit form method. How can I execute this controller from my IONIC app? Below is my CodeIgniter controller: function excel_kpa( ...

Set up a Pinia store with a specific data type

Note: I am a beginner in JavaScript I am currently working on synchronizing an object with a Pinia store and a Python REST API. My goal is to define a type just once without having to duplicate it in the store. export const useTicketStore = defineStore(&a ...

What is the process of embedding a string with pug code into a pug file?

How can I interpolate a string with pug formatted code in a pug file? Here is what I have tried: - var text = "i.home.icon" div= text div !{text} div #{text} div ${${text}} div {{text}} div {text} div \#{text} div \{text} div ${text} div # ...

Unlock the power of VueJS with advanced checkbox toggling for array data

I have encountered an issue while working with VueJS regarding the implementation of two features for a set of checkboxes. Initially, the checkboxes are generated dynamically. I am in need of a master 'toggle' checkbox that can toggle the stat ...

Tips on inserting text into form input fields

I need some guidance on how to enhance my form input functionality. The form currently consists of an input box and a submit button. When the user clicks submit, the form content is submitted and processed using javascript. What I am aiming for is to autom ...

Clicking on a single checkbox causes the entire input to become deactivated due to the way the system is

I'm encountering a puzzling issue that has me feeling like I know the solution, yet I don't. I set "State" to [checked]. The problem arises when, upon turning it into a map and clicking just one checkbox, the entire selection is clicked. To addre ...

express routes are failing to execute the function

When I navigate to routes in my browser, the results are displayed in my console but the server call seems to be running for a long time in the network. Can anyone provide some assistance? My controller, var express = require('express'); var ...

Executing PHP scripts in Javascript to monitor active online users: identifies individuals who are currently not authenticated

I am currently developing a basic admin panel and looking to allow logged in users to view other active users. To achieve this functionality, I have set up a sessions MySQL table containing active session data (logged in users) alongside a PHP file that up ...

Can Hapi-Joi validate a payload consisting of either an Array of objects or a plain Javascript object?

How can I create a schema to validate payloads for a post call that accepts either a single JS object or an array of objects to be saved in the database? JS object { label: 'label', key: 'key', help_text: 'text' } ...

Tips on Extracting Data from a JSON Object with an Embedded Array

Check out this example of a Json Object: {"UserName":Mike,"IsActive":0,"ChbxIsActive":false,"MyAccountsAvailable":[{"Id":"157A","MyAccount":"CHRIS MCEL","MyCheckBox":false,"Tags":null},{"Id":"157B","MyAccount":"DAN BONE","MyCheckBox":false,"Tags":null} He ...