Issues with the functionality of AngularJS checkboxes

I'm currently working on a basic AngularJS project to improve my skills. Below are the code snippets I've included. I have two sets of JSON data.

One set contains a list of grocery items, while the other set includes the items selected by the user. If the selected items match those in the collection, I want to mark the corresponding checkbox as checked. Inserting data upon checkbox click works fine, but if I randomly start unchecking items, it doesn't function properly. I'd appreciate any help to identify where I'm going wrong. I'd also like to know if there's a simpler way to compare JSON data. In my example, I'm using the name property for comparison. Is there a more straightforward way to compare individual objects inside the JSON without explicitly mentioning properties like name or type in AngularJS or JavaScript?

(function() {
  angular.module("groceryApp", []).controller("groceryController", groceryControllerFunction);
  groceryControllerFunction.$inject = ["$scope", "$filter"];

  function groceryControllerFunction($scope, $filter) {
    $scope.groceryCollection = groceryCollection_JSON;
    $scope.selectedItems = selectedItems_JSON;
    $scope.toggleSelection = function(item) {
      var isRemoved = false;
      if ($scope.selectedItems.length > 0) {
        for (var i = 0; i < $scope.selectedItems.length; i++) {
          if ($scope.selectedItems[i].name.indexOf(item.name) > -1) {
            $scope.selectedItems.splice($scope.selectedItems.indexOf(item), 1);
            isRemoved = true;
            break;
          }
          console.log("Checking..." + $scope.selectedItems[i].name.indexOf(item.name));
        }
      }
      //     else {
      if (!isRemoved) {
        $scope.selectedItems.push(item);
      }
      //   }
      console.log($scope.selectedItems)
    }
    $scope.addCustomItem = function() {}
  }
  var groceryCollection_JSON = [{
    "name": "Tomato",
    "type": "Roma"
  }, {
    "name": "Cauliflower",
    "type": "Organic"
  }, {
    "name": "Apple",
    "type": "Gala"
  }, {
    "name": "Orange",
    "type": "Sweet n' Sour"
  }, {
    "name": "Grapes",
    "type": "Wild"
  }];
  var selectedItems_JSON = [{
    "name": "Tomato",
    "type": "Roma"
  }];
})();
<!DOCTYPE html>
<html ng-app="groceryApp">

<head>
  <meta charset="utf-8">
  <meta name="description" content="First Angular App">
  <meta name="keywords" content="HTML, Javascript, AngularJs">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
  <script src="app.js"></script>
  <title>A simple AngularJs Application</title>
</head>

<body ng-controller="groceryController">
  <h1>Welcome to my Grocery Store</h1>
  <p>Select your items from the options below.</p>
  <div ng-repeat="item in groceryCollection">
    <input type="checkbox" id="{{item.name}}" value="{{item.name}}" ng-checked="selectedItems[$index].name.indexOf(item.name)>-1" ng-click="toggleSelection(item)">
    <label for="{{item.name}}">{{item.name}}</label>
    <input type="number" step="1" min="0" max="5" placeholder="Quantity" />
  </div>
  <p>
    <input type="checkbox" id="others">
    <label for="others">Others</label>
  </p>
  <p>Please Enter your item if not displayed in the list above:</p>
  <p id="extraItems"> <span><input type="text" placeholder="Please Enter your Item" ng-model="customItem"/></span>  <span><input type="text" placeholder="Please Enter your Item Type" ng-model="customItemType"/></span>  <span><input type="number" step="1" min="0" max="5" placeholder="Quantity"/></span> 
  </p>
  <p>
    <input type="button" value="Add Item" ng-click="addItem();" />
  </p>
  <p> <a href="#">Add more items</a> 
  </p>
  <div>
    <p>Your selected items:</p>
    <table>
      <tr>
        <th>Name</th>
        <th>Type</th>
      </tr>
      <tr ng-repeat="selection in selectedItems">
        <td>{{selection.name}}</td>
        <td>{{selection.type}}</td>
      </tr>
    </table>
  </div>
</body>

</html>

Answer №1

To simplify the process of item selection in the groceryCollection, you can use the selected flag directly on the items.

By eliminating the need for the toggleSelection function, you can reduce the code to

ng-click="item.selected = !item.selected"

Additionally, the ng-checked directive can be replaced with item.selected.

To display only the selected items, you can use

ng-repeat="selection in groceryCollection | filter: {selected:true}"

During the selection process, only the selected items are marked for easy identification.

(function() {
  angular.module("groceryApp", []).controller("groceryController", groceryControllerFunction);
  groceryControllerFunction.$inject = ["$scope", "$filter"];

  function groceryControllerFunction($scope, $filter) {
    $scope.groceryCollection = groceryCollection;
    
    $scope.addCustomItem = function() {}
  }
  var groceryCollection = [{
    "name": "Tomato",
    "type": "Roma"
  }, {
    "name": "Cauliflower",
    "type": "Organic"
  }, {
    "name": "Apple",
    "type": "Gala"
  }, {
    "name": "Orange",
    "type": "Sweet n' Sour"
  }, {
    "name": "Grapes",
    "type": "Wild"
  }];
  
})();
<!DOCTYPE html>
<html ng-app="groceryApp">

<head>
  <meta charset="utf-8">
  <meta name="description" content="First Angular App">
  <meta name="keywords" content="HTML, Javascript, AngularJs">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
  <script src="app.js"></script>
  <title>A simple AngularJs Application</title>
</head>

<body ng-controller="groceryController">
  <h1>Welcome to my Grocery Store</h1>
  <p>Select your items from the options below.</p>
  <div ng-repeat="item in groceryCollection">
    <input type="checkbox" id="{{item.name}}" value="{{item.name}}" ng-checked="item.selected" ng-click="item.selected = !item.selected">
    <label for="{{item.name}}">{{item.name}}</label>
    <input type="number" step="1" min="0" max="5" placeholder="Quantity" />
  </div>
  <p>
    <input type="checkbox" id="others">
    <label for="others">Others</label>
  </p>
  <p>Please Enter your item if not displayed in the list above:</p>
  <p id="extraItems"> <span><input type="text" placeholder="Please Enter your Item" ng-model="customItem"/></span>  <span><input type="text" placeholder="Please Enter your Item Type" ng-model="customItemType"/></span>  <span><input type="number" step="1" min="0" max="5" placeholder="Quantity"/></span> 
  </p>
  <p>
    <input type="button" value="Add Item" ng-click="addItem();" />
  </p>
  <p> <a href="#">Add more items</a> 
  </p>
  <div>
    <p>Your selected items:</p>
    <table>
      <tr>
        <th>Name</th>
        <th>Type</th>
      </tr>
      <tr ng-repeat="selection in groceryCollection | filter: {selected:true}">
        <td>{{selection.name}}</td>
        <td>{{selection.type}}</td>
      </tr>
    </table>
  </div>
</body>

</html>

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

Is it possible to execute an Ajax Request using JQuery?

I've been attempting to update the content within a <div> using a JQuery Ajax Call, but unfortunately I'm encountering some difficulties. Whenever I click on the onclick <a> element, nothing seems to happen. Below is the code that I a ...

Struggling to add an object to my Topic array using push

I'm in the process of developing a forum platform. Below is my Topic schema: const topicSchema = new mongoose.Schema({ author: { type: String, ref: "User", // Reference to the user who created the Topic required: true, }, t ...

AngularJS - anticipating the assignment of a value to a directive

I've encountered a peculiar issue while working with angularjs. I have a value bound to a directive, and I need to be able to check and manipulate that value from both the controller and a directive. Additionally, there is a method as a property of an ...

Using Django Rest Framework (DRF) to transmit an array of images as a

I need assistance with sending an array of images in a JSON format. My desired output is: {"id":1,"timeIntervel":4,"images":["http://127.0.0.1:8000/images/i1.jpg","http://127.0.0.1:8000/images/i2.jpg","http://127.0.0.1:8000/images/i3.jpg","http://127.0.0. ...

Tips for transferring information obtained from an API to my custom HTML page

As a novice in web development, I recently created a simple weather report website using the OpenWeather API. While I successfully fetched data from the API, I encountered an issue trying to display this data on my HTML page. Despite utilizing DOM manipu ...

Utilizing $routeParams to dynamically generate the templateUrl with AngularJS

Our platform offers a 2-level navigation system. We are looking to utilize AngularJS $routeProvider to dynamically load templates into an <ng-view />. Here is the approach I am considering: angular.module('myApp', []). config(['$route ...

What is the best method to showcase an array representing a key-value pair enclosed in {} as a list item within VueJS?

I have a specific object structure with a key that contains an array as its value. How can I present this information to the user in a list format? allComponents: [ {name: 'Standard field', uses: ['Inconsistent inputs', 'Formul ...

Traversing an array in C++ by using a pointer

Initially, I have a function that initializes an array and returns a pointer pointing to its first element. int* initializeArray() { int nums[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; return nums; } There is another function that simply creates an ...

Utilize clipboard functionality in automated tests while using Selenium WebDriver in conjunction with JavaScript

How can I allow clipboard permission popups in automated tests using Selenium web driver, Javascript, and grunt? https://i.stack.imgur.com/rvIag.png The --enable-clipboard and --enable-clipboard-features arguments in the code below do not seem to have an ...

Linking your Instagram account to your local account using Node.js and Angular

Currently, I am in the process of developing a MEAN app that will have local users with the capability to connect their Instagram accounts to it (not logging in using Instagram, but simply authorizing the app to access their images). At the moment, my app ...

Obtain file paths from a folder using JavaScript

Currently, I am in the process of developing an npm package that validates imported images. Can anyone provide some insights on how to instruct javascript to iterate through a specific directory and store the file paths in an array? Furthermore, my aim is ...

Tips for sending a JavaScript object to a Java Servlet

I'm facing a challenge with passing a JavaScript object to a Java Servlet. I've experimented with a few approaches, but nothing has worked so far. Below is the code snippet I've been working on: $.ajax({ url: 'TestUrl', d ...

AngularJS $resource sends the id as a query parameter rather than including it in the URL

I'm trying to retrieve data from a rest API by using the product id as part of the URL, rather than as a query parameter. Here is the factory code: .factory('Products', ['$resource', function($resource) { return $reso ...

Identifying the method of navigation using PerformanceNavigationTiming

Previously, I was able to determine if a user had arrived on the page by clicking the back button in the previous page using window.performance.navigation.type like this: if (window.performance.navigation.type === 2) { window.location.reload() } Howe ...

PhantomJS Karma encountering SyntaxError when trying to export variables

I've encountered an issue while running Karma and PhantomJS. When I attempt to run, the console displays the following message: 22 03 2016 14:58:47.865:WARN [karma]: No captured browser, open http://localhost:9876/ 22 03 2016 14:58:47.875:INFO [karm ...

Transforming the output of a MySQL query into a JSON format organized like a tree

This question has been asked before, but no one seems to have answered yet. Imagine a scenario where a MySQL query returns results like this: name | id tarun | 1 tarun | 2 tarun | 3 If we were to standardize the JSON encoding, it would l ...

Ways to prevent a <a href> element with a class linked to javascript from behaving like a block element

I am currently facing an issue with formatting an inline navigation. The last link, which is associated with a JavaScript class, is causing the entire link to become a block element instead of aligning inline with the rest of the links in the navigation. ...

Is there a way to see the countdown timers in Angular 7?

Is there a way for me to view my timer's countdown as it starts? I have attempted to bind it to a variable, but all I see is [object Object]: setTime(time) { if (this.settime >= 5 ) { this.currentTime = time; this.alerttime = thi ...

Issues with the functionality of the sliding menu in Angular are being encountered when trying to use $

Challenge I am facing an issue with a slider menu feature that I integrated into a mobile application for navigation purposes. The menu is functioning properly - it displays, allows flicking of the initial links, and can be closed by pushing the backdrop. ...

Click on the entire Material-UI formControlLabel to select it, not just the text

I have recently started working with the material UI. Currently, I am dealing with a form that looks like this: <FormControl variant="outlined" className={css.formControl} margin="dense" key={"abc_" + index} > <FormControlLabel cont ...