What is the best way to set checkboxes to default values using a model?

My journey with angular.js continues as I embark on creating my first non-tutorial web app. In this endeavor, I am utilizing two smart-tables and checklist-model for a seamless user experience. The initial table uses a st-safe-src of all_types, containing an array of JSON objects exemplified below...

[
  {
    "_id": "56417a9603aba26400fcdb6a",
    "type": "Beer",
    "__v": 0
  },
  {
    "_id": "56456140cb5c3e8f004f4c49",
    "type": "Skiing",
    "__v": 0
  },
  ...

Here's the HTML structure for the table displaying this data:


  <table st-table="displayedCollection" st-safe-src="all_types" class="table table-striped">
      <thead>
          <tr>
              <th st-sort="type">Types</th>
          </tr>
      </thead>
      <tbody>
          <tr ng-repeat="x in displayedCollection">
              <td><input type="checkbox" checklist-model="vendor.types" checklist-value="x.type">{{x.type}}</td>
          </tr>
          <tr><td>id ({{curid}}) {{vendor.types}}</td></tr>
      </tbody>
      <tfoot>
          <tr>
              <td colspan="5" class="text-center">
                  <div st-pagination="" st-items-by-page="itemsByPage" st-displayed-pages="7"></div>
              </td>
          </tr>
      </tfoot>
  </table>

The visual representation of this table upon data loading showcases checked checkboxes matching the model data.

To explore further, I then attempted replicating the above functionality in a second smart table featuring more detailed JSON objects like so...

[
  {
    "_id": "569f047dd90a7874025b344e",
    "product_title": "Plugs",
    "product_img_001": "p001.jpg",
    "product_img_002": "p002.jpg",
    "product_vid_001": "bp.mov",
    "__v": 0,
    "product_sizes": [
      "Large",
      "Med.",
      "Small",
      "10.5"
    ],
    "product_types": [
      "Running Shoe"
    ]
  },
  {
    "_id": "569f3958b108a7d70201b89a",
    "product_title": "Back Scratcher",
    "product_img_001": "http://itchy.png",
    "product_img_002": "http://relief-at-last.png",
    "product_vid_001": "my-itch",
    "__v": 0,
    "product_sizes": [
      "Large"
    ],
    "product_types": [
      "Rocks"
    ]
  }
]

Below is the corresponding HTML code used to visualize this data using another smart table:


  <table st-table="prodCollection" st-safe-src="all_products" class="table table-striped">
      <thead>
          <tr>
              <th st-sort="type">Products</th>
          </tr>
      </thead>
      <tbody>
          <tr ng-repeat="x in prodCollection">
              <td><input type="checkbox" checklist-model="vendor.products" checklist-value="x">{{x.product_title}}</td>
          </tr>
          <tr><td>{{vendor.products}}</td></tr>
      </tbody>
      <tfoot>
          <tr>
              <td colspan="5" class="text-center">
                  <div st-pagination="" st-items-by-page="itemsByPage" st-displayed-pages="7"></div>
              </td>
          </tr>
      </tfoot>
  </table>

Upon loading data into this table, I noticed that the checkboxes were not getting checked. A tweak in the code caused the correct checkboxes to be marked, yet only the product's title was being posted. How can one ensure both checked checkboxes and full product details are properly displayed?

An illustrative Plunker example has been provided: http://plnkr.co/edit/aPCEBV5e9Pb5np9iaY2l

Answer №1

Instead of using the Object as the checklist-value, you can utilize the id as suggested in the documentation section Array of objects (pick id)

<input type="checkbox" checklist-model="vendor.products" checklist-value="x._id">

If you prefer to use the Object as selected products (checklist-value="x"), you will need to incorporate checklist-comparator because the selected array and full product list do not have the same references in your plunker. The comparator should match equal objects by _id. Give this a try:

<input type="checkbox" checklist-comparator="._id" checklist-model="vendor.products" checklist-value="prod" />

Answer №2

If you use ng-true-value="1", it will compare the value with the ng-model and function similar to if(ng-model(Name) == 1). Give it a try.

<input type="checkbox" name="checkbox_demo_4" id="checkbox_demo_4"
    ng-model="temp.taxable_type"
    ng-true-value="1"
/>

In this scenario, 1 represents true value stored in the DB. Therefore, it automatically checks if the ng-model value includes 1. Good luck!

Answer №3

Having carefully reviewed your query and assuming you desire a similar functionality to the initial smart table, it appears that the issue you encountered can potentially be resolved by configuring the product_title as the checkbox value for the input field. See below for an example:

<input type="checkbox" checklist-model="vendor.products" checklist-value="prod.product_title" />

Feel free to check out the associated plunkr:

http://plnkr.co/edit/abcdef?p=preview

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

Having trouble capturing the 'notificationclick' event in the service worker when using Firebase messaging with Nuxt.js and Vue.js?

Experiencing difficulties in detecting events other than install, activate, or push in my firebase-messaging-sw.js. Notifications are being received and displayed, but I am unable to detect the event handler for notificationclick. When a firebase notificat ...

Organizing Results into Divs Based on Column Value Using AngularJs

I've been racking my brain trying to figure out the best way to organize and display my results in separate divs, specifically using Bootstrap col-md-4's. This is for a chat messaging app that I'm in the process of developing. I have rooms a ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

"Effortlessly rearrange and remove specific elements using jQuery UI's drag-and-drop

Hello everyone, I have designed a simple interface with 3 different "zones". The first zone contains a list of elements that the user possesses, the second zone allows the user to drag and sort these elements, and the third zone enables the user to delete ...

Unable to extract numerical value from the Volley response

I need to retrieve the document count from a remote MongoDB database by using a custom query URL. The URL only returns an integer value instead of a JSON object. In my Android application, I am utilizing Volley library to execute this query. However, when ...

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

Validating forms in Angular-CLI

The code below displays the output of my executed code: I am facing an issue with validations. Even when clicking the AddEmployee button without entering any data, it still gets added to the dataset. Below is the HTML code for app.component.html: <div ...

Smoothly scroll to the bottom of a dynamically updated div using native JavaScript

I am in the process of developing a chat application and my goal is to achieve a smooth scrolling animation that automatically moves the page down to the bottom of the div when dynamic messages are loaded. <ul id="messages"> <li ...

Are moment.js and moment.php interchangeable?

Recently, I developed a JavaScript script utilizing moment.js and I am looking to mirror it using a cron job in PHP. In my search for moment.js equivalents in PHP, I came across this https://github.com/fightbulc/moment.php ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

What is the intended use of the Newtonsoft.Json.JsonToken.StartConstructor token?

The JsonToken enum within the Newtonsoft.Json library's namespace features various entries, including JsonToken.StartConstructor. I may be interpreting this token incorrectly, assuming that JS constructor methods are not supported in JSON format, sim ...

JavaScript function to copy the first row of a table to the clipboard

I am new to JavaScript and I'm facing an issue with copying cells in a table. I have successfully created a table based on my MySQL database, but when I try to copy a cell using the copy button, only the first cell gets copied. I understand that I nee ...

Tips for inserting an element into every tier of a multi-layered array

I am faced with a challenging task of assigning an id field to objects within an array that has infinite levels. The rule is simple - for every level, the ID should correspond to the level number starting from 1. { "name": "Anything2&quo ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

The $http patch request is failing to transmit data to the server

Recently, I started utilizing AngularJS to create a CRUD functionality using Laravel and AngularJS. I have implemented a function that serves the purpose of both updating and saving data. Here is my function code: $scope.save = function (modalstate, id) ...

Generating a JSON string directly from the results of a database query

I am attempting to generate a JSON object based on the results of a database query. Here is an example of what I am trying to achieve: json_obj= { '1': 'test_1', '2': 'test_2', &apos ...

Looking to transform a nested JSON structure into a visually appealing HTML table with merged rows?

My JSON structure appears as follows: $scope.data = [ { "type":"Internal", "count": 3, "library" : [ { "type":"Library 123", "count": 2, "version" ...

Show a particular attribute from an array

My goal is to create a function that displays only minivans from an array of cars when a button is pressed. However, I'm having trouble getting anything to display when the button is clicked, even though there are no errors in the program. Any advice ...

Using the $.ajax function to make requests with CORS restrictions

Having some trouble with an AJAX request. I encountered the following error message: Error: Access is denied This is the jQuery AJAX request I attempted: $.support.cors = true; $.ajax({ url: 'http://testwebsite.com/test', type: "GET" ...

Utilizing React's multiple states for enhancing click event functionality

Here's the scenario: I am currently developing a Simon-Says game app using React Native. In this game, the user is shown a sequence of flashing buttons and must press them in the correct order. My main concern is figuring out how to utilize two diffe ...