Using AngularJS Services to Share Objects Between Views and Controllers

I'm finding it difficult to grasp the concept of AngularJS services as I am fairly new to AngularJS.

My goal is to pass a nested object between two controllers/views.

In my home page partial, I have a section that displays the project and task.

homePage.html

<div class="col-8" ng-repeat = "item in toDoList">
    <h4>{{item.project}}</h4>
    <p>{{item.task}}.</p>
</div>

And here is the section from the new item partial where users can add a new to-do task.

newitem.html

<form class="form" ng-submit="addNewToDoTask()">
    <div class="row projectInput text-center">
        <div class="col-12">
            <input type="text" ng-model="projectInput"
                   placeholder="Enter a project title">
        </div>
    </div>
    <div class="row taskInput text-center">
        <div class="col-12">
            <input type="text" ng-model="taskInput"
                   placeholder="Enter your task details">
        </div>
    </div>

    <button type="submit" class="btn-lg btn-success addItemButton">Add</button>
    <a href="#/"><button class="btn-lg btn-danger cancelButton">Cancel</button></a>
</form>

Here is my app.module.js

var app = angular.module('ToDoListApp', ['ngRoute']);

app.config(function ($routeProvider, $locationProvider) {

    $locationProvider.hashPrefix('');

    $routeProvider
        .when("/", {
            templateUrl: "app/home/homePage.html",
        })
        .when("/newItem", {
            templateUrl: "app/newItem/newitem.html",
        })
        .otherwise({
            redirectTo: '/'
        });
});

controller for home page

app.controller('homePageCtrl', function ($scope) {

});

controller for new item page

app.controller('newItemCtrl', function ($scope) {

    $scope.toDoList = [{
        project: null,
        task: null,
        done: false
    }];

    $scope.addNewToDoTask = function () {
        $scope.toDoList.push({
            project: $scope.projectInput,
            task: $scope.taskInput,
            done: false
        });
        $scope.projectInput = "";
        $scope.taskInput = "";
    };
});

service to persist data across views

app.service('newToDoTaskService', function () {

});

After submitting the form on the new item page, a new object is added to the toDoList array with the input values.

The next step is to use the project and task values from that object to populate the H4 and p tags on the home page.

Using a service seems like the best way to achieve this, but I need help understanding the concept even after reading the documentation.

If someone could explain how to accomplish this and break down the process, I would greatly appreciate it.

It's important to note that clicking the add or cancel buttons on the new item page will navigate you back to the home page.

Thank you

Answer №1

Feature to Persist Data Across Different Views with AngularJS

app.service('taskService', function () {
    var taskArr = [];
    this.getTasks = function() {
        return taskArr;
    };
    this.addTask = function(task) {
        taskArr.push(task)
    };
});

To implement this feature, you need to inject the service into the controllers:

Controller for Adding New Item Page

app.controller('newItemCtrl', function ($scope, taskService) {

    $scope.addNewToDoTask = function () {
        taskService.addTask({
            project: $scope.projectInput,
            task: $scope.taskInput,
            done: false
        });
        $scope.projectInput = "";
        $scope.taskInput = "";
    };
});

Controller for Home Page

app.controller('homePageCtrl', function ($scope, taskService) {

    $scope.toDoList = taskService.getTasks();

});

For further details and reference, visit

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

Converting a single 10GB zip file into five separate 2GB files with the help of NodeJS

var fs = require('fs'); var archiver = require('archiver'); var output = fs.createWriteStream('./test.zip'); var archive = archiver('zip', { gzip: true, zlib: { level: 9 } // Sets the compression level. }); ...

Clicking on a button will allow me to select only a portion of text within a specific cell of

Inside a table, there is a paragraph of text enclosed in a <td></td> element. Take for example the following passage. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

Distinguishing between a video or image when uploading files in JavaScript

I've been researching whether JavaScript can determine if a file is a video or an image. However, most of the information I found only shows how to accept these types using the input tag. What I really need is for JS to identify the file type and the ...

Dealing with the "TypeError: Cannot read property 'style' of undefined" error in material-ui Transitions: A troubleshooting guide

While attempting to incorporate transitions within my react app, I encountered a recurring error whenever I tried to implement any transition module: "TypeError: Cannot read property 'style' of undefined". (anonymous function) node_modules/ ...

Guide to creating a nested table with JavaScript

Currently, I am utilizing JavaScript to dynamically generate a table. To better explain my inquiry, here is an example of the HTML: <table id='mainTable'> <tr> <td> Row 1 Cell 1 </td> ...

What could be causing my Angular.js application to malfunction on IE7?

I have developed an Angular.js application that is working well on most browsers, but I am now facing compatibility issues with IE 7 and above. I have tried different approaches such as adding id="ng-app", using xmlns:ng, manually bootstrapping angular wi ...

Using jQuery, you can easily modify the color of a TD cell by applying the css properties assigned to the div element

I am attempting to implement a jQuery script that will execute upon the loading of the document. The objective is for the script to retrieve the background color of a div located within a td cell and apply it as the background color for the respective td c ...

How can the horizontal scroll bar width be adjusted? Is it possible to create a custom

Within my div, I have implemented multiple cards that scroll horizontally using the CSS property: overflow-x: scroll; This setup results in a horizontal scrollbar appearing under the div, which serves its purpose. However, I would prefer a customized scr ...

Tips for utilizing vulnerable web scripts on SSL-enabled pages

After implementing SSL to secure my pages, I encountered an issue where one of my scripts no longer functions properly. Specifically, I had a script on my page that was used to display the visit count from this website. Previously, it was functioning fla ...

Implementing server-side validation measures to block unauthorized POST requests

In my web application using angular and node.js, I am in the process of incorporating a gamification feature where users earn points for various actions such as answering questions or watching videos. Currently, the method involves sending a post request t ...

Display information from an array in checkboxes. If the same data appears in another array, the corresponding checkbox in React will be automatically checked

I currently have two arrays. The first array, let's call it arr1, contains multiple objects such as [{"Name":"Mr.X"},{"Name":"Mr.Y"},{"Name":"Mr.Z"}]. The second array, named arr2, holds a few values like [{"Name":"Mr.Z"}]. My goal is to display all ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

There are no leaks displayed in Chrome Dev Tools, however, the Task Manager will show them until Chrome eventually crashes

Do you have a CPU-intensive application that you're working on? Check it out here: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880 It involves a Canvas on which various elements are constantly being drawn. Here's the HTML ...

What is the best way to set the sidebar height to 100% in Material-UI?

Trying to learn MUI and encountered a problem. I want the sidebar to cover the full height, I tried 100vh but it stops increasing when the table extends. Using 100% only covers the end of the list. Is there another way to solve this, or is it fine becaus ...

Slider that allows range selection after midday

Currently facing a dilemma using the noUiSlider plugin. I have set up a time range picker starting from 6 am to 6 am the following day. Everything works smoothly until it reaches 23:59, but I need it to display 1:00, 2:00 instead of 25:00, 26:00 for the ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

What is the best way to maintain a div centered when the browser window shrinks smaller than the div's dimensions?

Is there a way to keep a div centered and create white space around it when the browser window is resized? I want this effect to happen whether the browser window gets larger or smaller. Currently, when the window size decreases, the left side of the div l ...

Unable to change the color of InputBase component's placeholder in React.js

I've been attempting to modify the color of the placeholder in an inputbase. I came across several methods online and tried implementing them, but none have been successful. Below are the codes I have tried. <InputBase id="input-id&quo ...

AngularJS: Issue with Variable Value Rendering

I recently started working with Angular. In my JavaScript file, I have the following code: App.controller('ProductController', ['$scope', 'ProductService', function ($scope, ProductService) { console.clear(); console. ...

Creating unique styles for components based on props in styled MUI: A comprehensive guide

One challenge I am facing is customizing the appearance of my component based on props, such as the "variant" prop using the 'styled' function. Here is an example code snippet: import { styled } from '@mui/material/styles'; const Remov ...