Transferring data between controllers within the Ionic Framework and Angular JS community

How can data be effectively shared between controllers using services in AngularJS?

For instance, when a user selects an item from the <ion-list> in services.html, the goal is to display the title of the selected item in service.html. The code snippet {{service.name}} illustrates what I am trying to accomplish.

services.html

    <ion-list>
        <ion-item ng-repeat="service in services" href="#/app/services/{{service.id}}" class="item-icon-right">
            {{service.title}} 
            <i class="icon ion-chevron-right icon-accessory">
                <span class="badge badge-positive">{{service.total}}</span>
            </i>
        </ion-item>
    </ion-list>

service.html

<ion-view view-title="Playlist">
    <ion-content>
        <h1>{{service.name}}</h1>
    </ion-content>
</ion-view>

controller.js

.controller('ServicesCtrl', ["$scope", "ServicesData", function($scope, ServicesData) {
  $scope.services = ServicesData.GetServices()
}])

.controller('ServiceCtrl', function($scope, $stateParams) {
});

services.js

angular.module('starter.services', [])

.service("ServicesData", [function () {

    var servicesData = [
        { 
            title: 'Car Repair and Maintenance', 
            total: 7, 
            id: 1 
        },
        { 
            title: 'Cleaning', 
            total: 1, 
            id: 2 
        },
        { 
            title: 'Delivery, Storage and Moving', 
            total: 6, 
            id: 3 
        }
    ];

    return {
        GetServices: function () {
            return servicesData;
        },
        GetServiceById: function () {
            // do stuff here to get the service by id
        }
    }
}])

Answer №1

angular.module('starter.services', [])

.service("ServicesData", [function () {

    var servicesData = [
        { 
            title: 'Car Repair and Maintenance', 
            total: 7, 
            id: 1 
        },
        { 
            title: 'Cleaning', 
            total: 1, 
            id: 2 
        },
        { 
            title: 'Delivery, Storage and Moving', 
            total: 6, 
            id: 3 
        }
    ];

    return {
        getSelected: function(serviceId) {
          var selectedService;
          
          servicesData.forEach(function(service) {
            if(service.id === serviceId) {
              selectedService = service;
            }
          });
          
          return return selectedService;
        },
        getServices: function () {
            return servicesData;
        }
    }
}])

.controller('ServicesCtrl', ["$scope", "ServicesData", function($scope, ServicesData) {
  $scope.services = ServicesData.getServices();
}])

.controller('ServiceCtrl', function($scope, $stateParams) {
  $scope.service = ServicesData.getSelected($stateParams.service);//the param name should be defined in the route config
});
<!--services.html-->

    <ion-list>
        <ion-item ng-repeat="service in services" href="#/app/services/{{service.id}}" class="item-icon-right">
            {{service.title}} 
            <i class="icon ion-chevron-right icon-accessory">
                <span class="badge badge-positive">{{service.total}}</span>
            </i>
        </ion-item>
    </ion-list>

<!--service.html-->

<ion-view view-title="Playlist">
    <ion-content>
        <h1>{{service.name}}</h1>
    </ion-content>
</ion-view>

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

Smoothly rotating an object in Three.js with a custom function

I successfully created a Rubik's Cube using Three.js, and everything is functioning as intended. However, I would like to add an animation when turning the cube instead of it snapping into place instantly. How can I achieve a smoother turning effect? ...

What is the process of linking MongoDB with a server?

My attempt to retrieve data from mongoDB while connecting to the server has led me to insert a value into mongoDB in the following manner: > use abc switched to db abc > db.ac.insert({name:"naveen"}) WriteResult({ "nInserted" : 1 }) > show coll ...

Encountered an error while attempting to interpret JSON data

I am currently attempting to utilize JQuery to parse a JSON response: <script> $(document).ready(function() { $("button").click(function() { $.ajax({ url : 'test.php', type : 'GE ...

The arrival of chat featuring Ajax, long-polling, and support for multiple users has finally

Imagine a site with three modules: "links", "home", and "chat". The "links" and "home" modules are static pages that do not require long polling. However, in the "chat" module, new messages may arrive at any time from other users, requiring an immediate up ...

Using JavaScript to parse JSON and set the value of a DatePicker

I have a text input field in my .cshtml page which is a Date type field. <div class="form-group"> <label for="comments">ETA:</label> <input class="form-control text-box single-line" data-val="true" id="MilestoneETAEdit" name ...

Change CSS style sheets depending on the size of the viewport

I've tried to implement the method from CSS-Tricks that allows for changing stylesheets based on the viewport width using multiple .css files and jQuery. However, my code isn't functioning as expected. I've spent the past hour trying to figu ...

Using Webpack to Compile Sass (and keep class names local)

It's been a long journey trying to configure my Webpack setup to compile Sass, and the process has become quite overwhelming. In my quest for answers, I encountered numerous Github issues, Stackoverflow threads, and blog posts discussing how to integr ...

Generate a table in MongoDB using NestJs without the need to create a new collection

I am facing a challenge with my app where I need to create an order with multiple attributes, one of which is an array of ordered products. Each object in the orderedProduct array must include the productId and the amount. However, I do not want to create ...

What is the process for updating selenium-webdriver if it is not globally installed on my system?

After installing selenium-webdriver with the command npm install selenium-webdriver (without the -g option), I found that the usual instruction of running webdriver-manager update did not work since it was installed locally. What is the correct way to upd ...

methods for transforming a string into an object

let styleValues = "{ "background-color": "#4a90e2", "padding": 10px }"; JSON.parse(styleValues); The code snippet above triggers the error below: Uncaught SyntaxError: Unexpected token p in JSON at position 46 ...

When using navigator.mediaDevices.getUserMedia on an iPhone, the webcam is activated in fullscreen mode

I'm facing an issue with the webcam functionality on my app. It works perfectly on Android and Windows, but when I try to use it on iPhone, the webcam opens in a separate full-screen view. Any ideas on how to resolve this? Thank you for your help in a ...

What is the best way to import modules in Typescript/Javascript synchronously during runtime?

I have a Typescript class where I am attempting to perform a synchronous import, however, the import is being executed asynchronously. My code snippet looks like this: --------------100 lines of code-------------------- import('../../../x/y/z') ...

What causes a ReferenceError when attempting to retrieve the class name of a React component?

Take a look at my React component located in index.js: import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { render() { return ( <div className="App"> <h1>Hello, ...

A guide on crafting OR queries in Elasticsearch using Node.js

I currently have a document structured like this: Sample document, [ { "_index": "xpertdox", "_type": "disease", "_id": "Ectopic Heartbeat", "_score": 24.650267, "_source": { "category": "Condition", "name": "Ectopic ...

Arranging currency values in Angular's UI-Grid widget

Need help sorting a grid column with dollar values that include $ and , as the sorting is not functioning correctly. Is there a solution to make the sorting work, or should I convert the values to numbers and then display them as money? Here is what I cur ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

Unable to employ the executescript method in Selenium with multiple arguments

I am currently working on automating a website to create a list through input values in a text field and setting them by clicking outside the field. Due to slow performance with Internet Explorer, I am using Selenium webdriver with IE. The sendKeys method ...

What is a common mistake when using refs in React?

I've recently started diving into React. I've seen conflicting opinions on using refs - some sources claim it's a bad practice altogether. Can someone clarify this for me? Is it harmful to attach refs to child components in order to access ...

Whenever I use jQuery to dynamically add a new form input, the Select2 input fails to function properly

For my form, I'm attempting to dynamically add a new form-row each time the user clicks the add button. <div class="form-row mb-2"> <div class="form-group col-md-3 my-2"> <label>File</label> ...

Tips for sending an array of inputs to the query selector in Node.js using Cloudant

Currently, I am attempting to retrieve documents from a cloudant database using node.js. While I have successfully managed to obtain results for a single input value, I am encountering difficulty when it comes to querying with an array of inputs. For a si ...