Sharing information between Angular controllers utilizing services

I am struggling with transferring data between controllers using a service. I expect that when the "send data" button is clicked, the information entered into the text field should appear in the Results controller. However, nothing seems to be showing up.

Home.html:

   <html>
<body>
<ion-header-bar class="bar-dark">
    <h1 class="title"></h1>
</ion-header-bar>
<ion-view view-title="Home">
    <ion-content ng-controller="StockUpdateCtrl">

    <div class="list">         
<ion-refresher pulling-text="Pull to Refresh" on-refresh="doRefresh()"></ion-refresher>
    <div>{{text}}</div>
    <input type='text' ng-model='text' />

     <button type='button' ng-click='send()'>Send Data</button>
     <div ng-controller='ResultsController'>
  <div>
    <h4>Ctrl2</h4>
    <div>{{text}}</div>
  </div>
</div>
    </ion-content>

</ion-view>
    </body>
    </html>

HomeController.js:

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


        .run(function ($ionicPlatform) {
            $ionicPlatform.ready(function () {
                // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                // for form inputs)
                if (window.cordova && window.cordova.plugins.Keyboard) {
                    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                }
                if (window.StatusBar) {
                    StatusBar.styleDefault();
                }
            });
        })


/*
 * Data Service 
 * Service used to pass data between controllers
 */
app.factory('dataShare', function(){
   var service = {};
  service.data = false;
  service.sendData = function(data){
      this.data = data;
      $rootScope.$broadcast('data_shared');
  };
  service.getData = function(){
    return this.data;
  };
  return service;
});

/* 
 * Stock Update Controller
 * Gets user input and then performs calculations to prepare to be displayed
 * 
 */
app.controller("StockUpdateCtrl", function ($scope, $http, dataShare) {


    $scope.text = 'Hey';
         $scope.send = function(){
           dataShare.sendData($scope.text);
         };



});

ResultsController.js:

 * Resultse Controller
 * Displays the results
 * 
 */
app.controller("ResultsController",function ($scope, dataShare) {

    $scope.text = '';
                $scope.$on('data_shared',function(){
                            var text =  dataShare.getData();    
              $scope.text = text;
        });
});

Answer №1

Ha, I finally figured it out! It turns out the issue was with how I was calling the results page. I had to remove the form tag.

<form action="index.html#/results" ng-controller="StockUpdateCtrl">

Instead, I changed my button to call the results page like this:

<button type="submit" ui-sref="results"  ng-click="calculate()" class="button button-block button-balanced">

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

establishing communication between the angular controller and route controller

index.html <body> <div data-form-modal > <form> <input type='text' name='test'/> <input type='submit' value='submit' ng-click='submit()'/&g ...

Visualizing Data with HTML and CSS Chart Designs

I'm seeking assistance with creating an organization tree in a specific layout. https://i.sstatic.net/z9LRc.jpg I am having trouble replicating the tree structure shown in the image. I need help generating a similar tree structure where multiple le ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Is it possible to customize the appearance of specific characters within an input field?

One of our clients has inquired about incorporating the type="number" attribute for a credit card field to ensure the appropriate keyboard is displayed on mobile devices. However, they also want to add padding after every 4th character to mimic the appea ...

Why is it that in Angular, the child controller shares the same scope as the parent?

I have set up a testing environment on Plunker, here is the link to the full example: View the complete example on Plunker Below is the child controller code snippet that is functional: child.directive('child', function(){ return{ r ...

Emphasize an element when hovering over it

I am looking to create a custom hover effect for highlighting elements in a Chrome extension I'm developing. The goal is to achieve a similar behavior to using the magnifying glass tool in Chrome Dev Tools, where only the hovered element is highlighte ...

Instructions for accessing and printing text from a nested ul tag with Selenium in Java

Hello everyone, I am currently learning about Selenium Automation and have created a website as shown below. Here is the HTML code: <!DOCTYPE html> <html> <head><title>Shop</title></head> <body> <ul> < ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...

My goal is to generate a collection of fullwidth ion-cards using data from an array of objects

I am attempting to iterate through an array of objects in order to generate a set of cards, either FULLWIDTH or halfwidth with the last one centered if the count is an odd number. I have created a component that contains the card layout and I am using *ng ...

Disappearance of PNG arrow upon focusing on element

I could really use some assistance with this issue. I'm scratching my head trying to pinpoint the root cause of the problem at hand. The image below illustrates the desired effect I'm aiming for with HTML coding, showcasing the before (left) and ...

Issue with AngularJS: $http header 'Content-Type' not being appended to the header

When making a GET request using $http, I encountered an issue where I needed to append 'Content-Type': 'application/json' in the header to avoid getting a 415 (Unsupported Media Type) error. I am running Apache 2.2.13 with ProxyPass an ...

Overflow causes flexbox to become unreactive

Implementing the overflow style on a flexbox element appears to negatively impact its responsiveness. Here is the corresponding code snippet: .projects-wrapper{ display: flex; flex-wrap: wrap; justify-content: center; text-align: center; width ...

An exciting tutorial on creating a animated dropdown using vueJS

I've set up a navigation menu with mouseover and mouse leave events to toggle a dropdown by changing a boolean value. Now, I'm trying to apply different animations to the list items in the dropdown compared to the surrounding box, but I'm f ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

Perfect alignment in a vertical position can be hard to achieve down to

My goal is to perfectly vertically align the title inside the navigation panel. However, upon inspecting the screenshot images in an image viewer, I noticed a 1px gap at the bottom which makes the vertical alignment pixel-imperfect. https://i.sstatic. ...

Enhance your website with a multi-column Pure CSS drop-down menu

Can anyone help me with this issue I'm facing? I am struggling to add a second column to the main "Authorized Brands" menu, and when I tried to break it up, it affected the rest of the columns due to the width being set at 1000px. This is the code I ...

Using jQuery for slide shows in Ruby on Rails framework

I'm attempting to create a slideshow using jQuery and have the images stored in an array. However, I'm struggling with the implementation of the slideshow functionality. I've checked out 'http://jquery.malsup.com/cycle/' for guidan ...

The server's response returned a 400 HTTP status code along with the error that the requested resource does not have the 'Access-Control-Allow-Origin' header. This issue is common in MEAN

I'm in need of sending a string to the node and receiving the following response in the browser console: Failed to load http://localhost:3003/api/buscarCep: No 'Access-Control-Allow-Origin' header is present on the requested resource. Ori ...

Is there a method to use media queries to dynamically switch JavaScript files based on the user's device?

I've been working on optimizing the mobile layout of my website, and while I have successfully implemented a media query with a different stylesheet for mobile devices, I'm struggling to determine if it's feasible to also load a separate Jav ...

The loading icon appears stuck and does not rotate on iOS version 15.3 and above, but functions properly on versions below 15.3

The loading icon does not spin on iOS versions > 15.3 or 16.1, but it works perfectly fine on lower iOS versions for iPhone and iPad, as well as on Android browsers. Below is the CSS code for reference. I've attempted using webkit for Safari and a ...