Sharing information between controllers in OnsenUI using AngularJS and PhoneGap

I've encountered similar questions to mine that have been addressed, but I believe my scenario is unique. I began with the sample code available on this page for a basic app featuring a sliding menu integrated with Google Maps.

My current project involves creating a prototype allowing users to submit new items, which are then added to a list of pending submissions and displayed on the map. Currently, I am focused on enabling users to create items and automatically updating the list of pending submissions. I have implemented a simple form for creating new items:

<ons-page>
    <ons-toolbar fixed-style ng-controller="SlidingMenuController">
        <div class="left">
            <ons-toolbar-button ng-click="slidingMenu.toggleMenu()"><ons-icon icon="bars"></ons-icon></ons-toolbar-button>
        </div>
        <div class="center">New Submission</div>
    </ons-toolbar>
    <ons-row style="margin-top: 10px; text-align: center;">
        <ons-col ng-controller="NewSubmissionController">
            <p style="font-size: 12px;">Please provide a brief description and material details of your find.</p>
             <textarea style="width: 97%;" id="subDescrText" class="textarea" rows="4" placeholder="Type your description here..." value="" ng-model="subDescription"></textarea>
        <ons-button style="margin-top: 24px;" ng-click="doStore()">
            Store
        </ons-button>
        </ons-col>
    </ons-row>
</ons-page>

Another page has been set up to display the created submissions:

<ons-page>
    <ons-toolbar>
        <div class="left">
            <ons-toolbar-button ng-click="slidingMenu.toggleMenu()"><ons-icon icon="bars"></ons-icon></ons-toolbar-button>
        </div>
        <div class="center">Pending Submissions</div>
    </ons-toolbar>
    <div style="text-align: center;">
        <ons-list id="pendingList" var="aPendingList" ng-controller="PendingListController">
            <ons-list-item ng-repeat="pi in pendingItems">
                <p>{{pi.description}}</p>
                <span>{{pi.material}}</span>
            </ons-list-item>
        </ons-list>
    </div>
    <p style="margin-top: 12px; text-align: center; width: 100%;" >
        <ons-button ng-click="">
            Upload All
        </ons-button>
    </p>
</ons-page>

The necessary controllers have also been added:

app.controller('NewSubmissionController', function($scope) {
    $scope.selMat;
    $scope.subDescription;

    $scope.doStore = function() {
        alert('In NewSubmissionController.doStore() - Selected material: ' + $scope.selMat + '\nDescription: ' + $scope.subDescription);

        var newPI = new SubmissionItem($scope.selMat, $scope.subDescription, '');
        $scope.$emit('newPI', newPI);
        slidingMenu.setMainPage('pendingList.html', {closeMenu: true});
    };

});

// Controller for Pending List
app.controller('PendingListController', function($scope) {
    $scope.pendingItems = [];
    $scope.$on('newSubEvent', function(e, subMat, descr) {
        alert('In PendingListController, event newSubEvent - Submitted material: ' + subMat + '\nDescription: ' + descr);
    });

    $scope.addPendingItem = function(newPi) {
        alert('In PendingListController.addPendingItem() - ' + newPi);
        $scope.pendingItems.unshift(newPi);
        // Code to update the list of pending submissions...
    };
});

In my attempt to utilize the event system based on suggestions, it appears ineffective as the two controllers are not linked hierarchically. Even placing PendingListController within NewSubmissionController proved futile likely due to both being part of separate views.

What would be the most efficient solution to trigger PendingListController.addPendingItem() from NewSubmissionController?

Answer №1

When working with multiple pages and requiring the management of different pages, it is recommended to implement the Multiple Pages Managing Pattern. This involves adding a main controller for the main navigation page, such as a sliding menu page, to enable sharing of $rootScope among child controllers.

One effective solution is to utilize Dependency Injection, where you can use services or factories to facilitate the passing and sharing of data between controllers.

The demonstration code below illustrates:

  • How to utilize a service for communication between controllers
  • How $rootScope can be used for live updating of data

Implementing a service to facilitate data sharing between controllers:

angular.module('app', [])
  .service('mainService', function($http) {
    var self = this;
    self.userList = [];

    self.login = function(newUser) {
      self.userList.push(newUser + ' ' + (self.userList.length + 1));
      return self.userList;
    };
  })

.controller('MainCtrl', function($rootScope, $scope, mainService) {

  $scope.mainAddUser = function() {
    $rootScope.users = mainService.login('Main');
  };
})

.controller('LoginCtrl', function($rootScope, $scope, mainService) {
  $scope.loginAddUser = function() {
    $rootScope.users = mainService.login('Login');
  };
});

For a live demo, visit http://plnkr.co/edit/OvG0oj6EmDU5GMi1eBaU?p=preview

Answer №2

To effectively communicate and handle events between controllers that do not share the same $scope, utilize $rootScope along with its functions $on and $broadcast:

myApp.controller("fooCtrl", function($scope, $rootScope){
        $scope.foo = "foo";

        $scope.broadcast = function() {
            $rootScope.$broadcast("fooChange", $scope.foo);
        };
});

myApp.controller("barCtrl", function($scope, $rootScope){
        $scope.bar = null;

        $rootScope.$on("fooChange", function(e, data){
            $scope.bar = data;
        });
});

Upon capturing the event in barCtrl, you can execute the

PendingListController.addPendingItem()
method.

Check out the DEMO at http://jsbin.com/kolorixoti/1/edit?html,js,output

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

Trigger the activation of an input field upon clicking an image labeled "edit"

I am currently developing a website where administrators have access to a dashboard page that displays a list of users. I am looking to implement a feature that allows admins to change the roles of other users directly from the same table row. Below is th ...

Ways to retrieve a variable from outside of a function

I am in need of sending the following batch data to the database, but I am facing difficulties in including the course_id along with the batchData. Currently, I am retrieving the course_id from another service that fetches data from a course table. I am ...

Having trouble redirecting to the Google login screen with Passport Google Auth 2.0

Greetings, I have encountered an issue with my server setup. I am attempting to redirect users to the Google authentication screen when they navigate to the /auth/google path. However, instead of being redirected, I am consistently landing on my 404 error ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

Enhancing your JQuery Select2 plugin by incorporating a Checkbox feature

I am currently utilizing the jQuery select2 plugin to enable multiple selections. My goal is to incorporate a checkbox for each selectable option. Depending on whether the checkbox is checked or unchecked, the dropdown option should be selected accordingl ...

Error encountered with React Hooks - TypeError

What I Aim to Achieve Our goal is to utilize Next.js to create a button named 'ConnectMetamask' that, upon clicking, triggers the predefined hooks and stores the value in a variable called 'userSigner'. This functionality is implemente ...

Loading static assets in Express.js

I am currently utilizing express for developing a web application. However, I am encountering issues with my routes and static files. I have included a reference to static files: app.use(express.static(path.join(__dirname, 'public'))); and conf ...

The system does not acknowledge "ENVIRONMENT" as a command that can be executed either internally or externally, or as a batch file that can be

While running my Next.js application, I encountered the following error in a script: "scripts": { "dev: "ENVIRONMENT=env/.env.development next dev", "check": "npm run format && npm run eslint", "e ...

Ensure that PHP form validations are checked when submitting the form using jQuery

I have created a form in HTML with basic verification. Here is the code: <form class="" action="submit/save" method="POST" enctype="multipart/form-data" id="submit_form"> <input class="form- ...

Generate a variety of requests with Axios

I have a task where I need to send multiple Axios requests, but the number of requests can be completely random. It could range from 0 to even millions. Once all the requests are completed, I then need to perform an action, such as updating my state, which ...

Jump to Anchor when Page Reloads

Hey there! I'm currently developing a gallery script and I'm trying to figure out how to automatically position the page to the top of a specific anchor when it is loaded. I attempted to use the following code: <script>location.href = "#tr ...

Angular 1.x just got a major upgrade with the introduction of the UI-Router v1.0+ $trans

I am on the hunt for a method that can replicate the functionality of UI-Router's $rootScope.$on('$stateChange...' from before version 1.0. Although I am aware of the new $transitions service, I am struggling to get it to work in the same wa ...

Getting a portion of a href link in Java using Selenium

I am looking to compare the current URL in Google Chrome with a specific href link that contains two URLs. I need to extract the first link from this specific href link: click here <a href="http://pubcontentqa.perion.com/dz2/html/interstitial.html?http ...

What is the best way to save a scheduled cron reference in a database in order to deactivate it at a later time in a

I have implemented a system using cron to schedule push notifications. The user provides the push notification data and the scheduled time, and I use cron to send the notifications at the specified time. Below is the code snippet showing how I create a cr ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

What is the best way to enforce a required selection from one of the toggle buttons in a React form?

Is there a way to require the user to click one of the toggle buttons in a react form? I need to display an error message if the user submits the form without selecting a button. I tried using the "required" attribute in the form but it didn't work. H ...

Problems arise when a controller within an ng-repeat needs to pass data to another controller, based on the specific ng-repeat element that was clicked

My goal is to achieve the following: I am working with two controllers that communicate with each other through a service (Check out my code on jsFiddle: http://jsfiddle.net/GeorgiAngelov/a9WLr/1/). The concept: The concept here is to have changes made ...

What are the steps to showcase a randomly generated number in a live Flot chart using Json?

In my C# page, I have created a random number stored in a json object: if (method == "rnd") { //Random number this.Page.Response.ContentType = "application/json2"; Random rnd = new Random(); int nr = rnd.Next(1, 100); // generates a number ...

The information does not display in the AngularJS-generated table

Struggling with AngularJS directives? Let's take a look at the code: <div ng-controller="Controller"> <table> <thead> ....... </thead> <tfoot> ....... </tfoot> <tbody> < ...

Using nodeJS to showcase content on a web page

I'm relatively new to NodeJS, and I am trying to figure out if there is a way to utilize NodeJS similar to JavaScript. My goal is to retrieve data from a database and display it within a div on my index.html page. When attempting to use querySelector, ...