AngularJS - Issue with Checklist-Model not accurately reflecting changes in the model when checkboxes are toggled

Recently delving into AngularJS, I encountered a puzzling issue with the Checklist-Model directive.

To replicate the problem, I followed one of their examples. Upon clicking a checkbox and invoking a function, the model reflects the update correctly on the template. However, upon inspecting the console log, I notice that the value of the clicked checkbox is missing. The oddity escalates when clicking the checkbox again - this time, the value disappears from the template but remains visible in the console.

Here's the snippet of code:

HTML:

<div ng-controller="DemoCtrl">
      <label ng-repeat="role in roles">
          <input type="checkbox" checklist-model="user.roles"
                 checklist-value="role.text"
                 ng-change="changeValues(role)"> {{role.text}}
      </label>
  <br>
  <button ng-click="checkAll()">check all</button>
  <button ng-click="uncheckAll()">uncheck all</button>
  <button ng-click="checkFirst()">check first</button>
  <br><br>
  user.roles {{ user.roles | json }}
</div>

Angular:

angular.module("DemoApp", ["checklist-model"])
.controller('DemoCtrl', function($scope) {
$scope.roles = [
    {id: 1, text: 'guest'},
    {id: 2, text: 'user'},
    {id: 3, text: 'customer'},
    {id: 4, text: 'admin'}
  ];
  $scope.user = {
    roles: ['guest', 'admin']
  };
  $scope.checkAll = function() {
    $scope.user.roles = $scope.roles.map(function(item) { return item.id; });
  };
  $scope.uncheckAll = function() {
    $scope.user.roles = [];
  };
  $scope.checkFirst = function() {
    $scope.user.roles.splice(0, $scope.user.roles.length); 
    $scope.user.roles.push(1);
  };

    $scope.changeValues = function() {
    console.log('Roles: ', JSON.stringify($scope.user.roles));
  }
});

Upon clicking a checkbox for the first time, say 'User,' the console output shows:

Roles: ["guest","admin"]

Subsequently unchecking the same checkbox yields:

Roles: ["guest","admin","user"]

The application necessitates calling a function upon checkbox value change, which led me to utilize the "ng-change" directive.

If anyone can shed light on where I might be erring, it would be greatly appreciated. Thanks in advance.

Answer №1

checklist-model allows you to use the ID as the checklist-value in the checkbox, while your code is using the text instead. In the $scope.checkAll function, make sure to return item.text instead of item.id. Similarly, in the $scope.checkFirst function, remember to push $scope.roles.find(item => item.id == 1).text. Everything else appears to be correct.

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

PHP while loops that result in an never-ending loading loop

I am attempting to upload an image and some alphanumeric characters using AJAX. The code seems to be functioning correctly (i.e., all data is being successfully stored in the database) except for a crucial issue. I need the "character" variable to be uniqu ...

The property cannot be set for an undefined element in Jquery UI slider tabs

There seems to be some extra space at the bottom of the slider tabs between the navigators and content. Additionally, I am facing a challenge in making the page responsive as the content size does not adjust when I resize the window. To see the changes, I ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...

What is the best way to add two strings with indexes and points to a Three.js BufferGeometry?

I have a massive database containing tens of thousands of objects with various types of information, including their 3D meshes. Currently, I am attempting to display these objects in web browsers using Three.js. The object information is provided by anoth ...

Encountered an error while attempting to insert a new user into a MySQL database using the Node, Express, and MySQL package

Currently in the process of creating a CRUD API using NodeJS. My main goal at the moment is to execute a POST request to add a new user to the database. The issue I am facing is that although I can successfully add a new user to the database, my server cra ...

I must condense an array

How can I flatten an array of objects: var mylist = [{ THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children: [{ ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1" }, ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

Confirmation of successful form submission

I have created a form to collect user details. Once the form is submitted, the page reloads. I am looking to show a success message after the page reloads. <form name="myForm" class="contactus-template" method="post" onsubm ...

Jasmine spying on a standalone function that is not a method of an object

What is the best way to spy on a function that is not a method of an object? In my specific case, the function callMe is not defined on the window object - it is a dependency loaded through angular. if (X) { callMe('hello'); } ...

Enhancing the Angular UI Bootstrap Accordion: Customizing the header with a new class

I currently have a functional accordion implemented as shown below <accordion-group is-open="open.first"> <accordion-heading> My Title </accordion-heading> </accordion-group> The "Accordion-heading" direc ...

Implementation of Exporting to Excel

function fnshowAuditList() { if(auditListTable) auditListTable.fnDestroy(); jQuery.ajax({ type: 'POST', url: 'auditListAction', data: '', dataType: 'text&a ...

Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner: angular.module('xpto', ['ngResource']) .factory('XPTO', function ($resource, $location) { var XPTO = $resource($location.protocol() + '://' + $locatio ...

Utilizing AJAX to automatically fill out a form with information retrieved from a MySQL database

I have been attempting to automate the population of a form with data when a gymnast is selected from a dropdown box. I am aware that AJAX needs to be used for this purpose, and despite my best efforts, my lack of proficiency in Javascript has resulted in ...

Building XML using PHP with relatively extensive information stored in JavaScript

Similar Question: XML <-> JSON conversion in Javascript I have a substantial amount of data stored in JavaScript that I need to convert into an XML file on the PHP server. The process of transforming the data into a JSON object, sending it to PH ...

Vue - Find matching data in an array of objects and render it on the page

I have a Vue.js data array that contains information about counties in the UK. I want to create links between related county pages based on the data in the array. To achieve this, I need to loop through the main county object and compare the items in the ...

Lens Flare Troubles in Three JS

I'm having trouble implementing the LensFlare Effect from the three js docs in react three fiber. I've tried using the code provided but it's not working for me. Here's what I have: import { extend, useLoader } from "@react-three/f ...

Utilizing Inquiries within Arrays

I've been working on a quiz application and I have successfully built the array with questions and answers. However, I'm facing some challenges in getting the next question to display after clicking the submit button. Here is a snippet of the cod ...

Convert an array comprising arrays/objects into JSON format

This problem is really challenging for me. The structure of my array goes like this: array1 = [ [array2], [array3], [array4] ... [array17] ] array2 = [ ['obj1'], ['obj2'], ['obj3'] ... ['obj30'] ] ... ... obj1 = ({p ...

Utilize the fitBounds feature from GoogleMaps in Vuejs for seamless integration

I've been working on getting the map boundaries to work properly, using a method in conjunction with my existing initMap and askGeolocation methods. Despite my best efforts, I can't seem to get the bounds functionality working so that the map zo ...