Collaborating information between 2 controllers using a shared Service in Angular.js

(function () {
'use strict';

angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service("ShoppingListCheckOffService", ShoppingListCheckOffService);

ToBuyController.$inject = ["ShoppingListCheckOffService"];

function ToBuyController(ShoppingListCheckOffService) {

  var buyItem = this;

  buyItem.items = ShoppingListCheckOffService.getItems();
  buyItem.removeItem = function (itemIndex) {
  ShoppingListCheckOffService.removeItem(itemIndex);
  }
}

AlreadyBoughtController.$inject = ["ShoppingListCheckOffService"];
function AlreadyBoughtController(ShoppingListCheckOffService){
    var boughtItem = this;

    boughtItem.itemName = "";
    boughtItem.itemQuantity = "";
    // console.log(boughtItem.name);


    boughtItem.items = function () {
      ShoppingListCheckOffService.addItem(boughtItem.itemName, boughtItem.itemQuantity);
    }

  //  boughtItem.items = ShoppingListCheckOffService.getItems();

  }


function ShoppingListCheckOffService() {
  var service = this;

  // List of shopping items
  var items = [{
    name: "Donuts",
    quantity: "200"
  },
  {
    name: "Cookies",
    quantity: "10"
  },
  {
    name: "Cake",
    quantity: "1"
  },
  {
    name: "Bread",
    quantity: "2"
  },
  {
    name: "Candies",
    quantity: "30"
  }
];

  service.addItem = function (itemName, itemQuantity) {
    var newItems = [];
    var item = {
      name: itemName,
      quantity: itemQuantity
    };
    newItems.push(item);
    return newItems;
  };

  service.removeItem = function (itemIndex) {
    items.splice(itemIndex, 1);

  };

  service.getItems = function () {
    return items;
  };
}

})();

HTML Code:

<!-- To Buy List -->
    <div class="col-md-6" ng-controller='ToBuyController as buyItem'>
     <h2>To Buy:</h2>
     <ul>
       <li ng-repeat="item in buyItem.items">
         Buy {{item.quantity }} of {{ item.name }}
         <button ng-click="buyItem.removeItem($index)" class="btn btn-default"><span class="glyphicon glyphicon-ok">Bought</button>
       </li>
     </ul>
     <div class="emptyMessage">Everything is bought!</div>

    </div>

    <!-- Already Bought List -->
    <div class="col-md-6" ng-controller='AlreadyBoughtController as boughtItem'>
     <h2>Already Bought:</h2>
     <ul>
       <li ng-repeat="item in boughtItem.items">
         Bought {{ item.quantity }} of {{ item.name }}
       </li>
     </ul>
     <div class="emptyMessage">Nothing bought yet.</div>
    </div>

Modify the code so that clicking on "Bought" removes an item from one list and adds it to another. Two different controllers are used under the same Service. The addItem() method under the controller "AlreadyBoughtController" needs debugging.

Answer №1

In the addItem function, you are currently creating an empty array and then adding the item to it. To make this process more efficient, you should update your addItem method as shown below:

service.addItem = function (itemName, itemQuantity) {    
    var newItem = {
      name: itemName,
      quantity: itemQuantity
    };
    items.push(newItem);
    return items;
  };

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

Extracting textual information from Wikipedia through iframes?

Currently, I am working on a website project utilizing Squarespace. This site will feature multiple pages dedicated to individuals who have reached a level of notability worthy of having their own Wikipedia page. With over 150 pages planned, manually writi ...

What causes an asynchronous function to exhibit different behavior when utilized in conjunction with addEventListener versus when manually invoked?

I was delving into the concepts of async and await keywords and decided to create a basic demonstration using an HTML file and a corresponding JS file. In my example, I defined two promises - promise1 and promise2. The handlePromises function uses async/ ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

Error: Invalid argument type. The argument "chunk" should be either a string or a Buffer, instead of a number

Currently, I am working on a problem on HackerEarth and utilizing JavaScript for the task. Here is the code I have implemented: // Sample code to perform I/O: process.stdin.resume(); process.stdin.setEncoding("utf-8"); var stdin_input = ""; process.stdin ...

Transforming a canvas element into an image sans the use of toDataURL or toBlob

Recently, I developed a small tool which involves adding a canvas element to the DOM. Strangely, when trying to use toBlob or toDataURL, I encountered an issue with the canvas being tainted and received the error message (specifically in chromium): Uncaugh ...

Deactivate a component in React Js

Starting out in the world of react Js and looking to disable certain elements based on conditions Within my form, I have a select element and two input elements Depending on the selected item, one of the input elements should be disabled Here is a snipp ...

The issue with updating state in React using dispatch within the same method is not working

Initially, I had a situation where the state was updating correctly with two separate methods (onClick). const sizesMeasureChoise = useSelector(getSizesMeasureChoise); const chooseMeasure = (measure) => { dispatch(setSizeMeasureChoise(measure)); ...

AngularJS - Show alert message when email format is incorrect on Textbox Blur

I have set up AngularJs email validation in the following way: <div class="control-group" ng-class="{'has-success': contactform.contactemail.$valid && submitted,'has-error': contactform.contactemail.$invalid && s ...

Dealing with unhandled exceptions while passing promises into pg-promise batch transactions

Currently, I am diving into the realm of learning express and pg promise. However, during this journey, I have encountered a puzzling issue that I suspect stems from my somewhat shaky understanding of promises. Essentially, I have crafted some functions f ...

Is there a way to trigger the mouseover event on every element currently under the cursor?

In my web application, I have a feature where a dot is created every time you click. However, when hovering over a stack of dots, only the top dot triggers the mouseover or mouseenter event. How can I ensure that the events fire for every dot under the cur ...

Send two values from a select box when it is chosen

I am currently facing a challenge where I need to retrieve two related values when a select box is changed. The select box is set up to allow multiple selections and contains options that represent user resources, some of which are parent resources. My goa ...

Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery? My element has a relative position, so the offset() function only gives me the offset within the parent. Unfortunately, I have hierarchical divs, ...

Delay the execution of an AngularJs directive for later processing

I am seeking a way to delay the execution of a nested directive until after an asynchronous task is completed by its parent directive. While I can achieve this easily with two lines of jQuery, I am curious if there is a purely Angular approach using $q. Y ...

Acquiring the safe area of the iPhone X through JavaScript

The CSS properties safe-area-inset-left, safe-area-inset-right, safe-area-inset-top, and safe-area-inset-bottom are available, but is there a way to retrieve these values using JavaScript? ...

Retrieve the offsetTop value of an accordion following its collapse

My goal is to determine the exact position of a clicked accordion title after it has been clicked. The issue I am facing is that the movement of Bootstrap's accordion collapse and my jQuery function are triggering almost simultaneously. As a result, ...

Encrypt requests with AES within a Node.js proxy server

Is there a streamlined approach in building an Express application to create a route that forwards the request to another server, encrypts the response before delivering it to the client for decryption? Can this be achieved entirely through streams? ...

what is the best way to activate components within a directive template externally?

Having trouble accessing DOM elements outside the app.js that are created by the directive in AngularJS. What is the best approach to solve this issue? I am new to AngularJS and appreciate any suggestions. app.directive('myMenu', function() { ...

discord.js: Imported array not displaying expected values

I've been facing an issue with accessing elements from an imported array. Even though the array is successfully imported, attempting to access its elements using [0] results in undefined. Here's how I exported the array in standList.js: exports. ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

When attempting to pass data to another page by clicking on a row, the result is that the data appears to be empty

I have been using the MUI-Datatable component, which is able to navigate to the next page. However, when I try to view the data on the History page, nothing appears. How can I resolve this issue? Data transfer to another page: Even though I can see the d ...