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

I am looking to host several iterations of jQuery on a content delivery network within my Nuxt application

Currently, we are loading jQuery 3.1.4 externally from a CDN on the top page. index.vue head: { bodyAttrs: { id: 'overview' }, script: [ { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min ...

What is the process for creating a filter to refine ng-model values in AngularJS?

One of the challenges I am facing involves an input field: <input type="text" ng-model="defaultValue"> Within my controller, the input field is initialized as an empty string: $scope.defaultValue = ""; I aim to develop a filter that can compare v ...

Exploring SQL Components with JavaScript

Here is the code I am currently using: //This function handles all games and their attributes function handleGames(){ sql.query('SELECT id FROM games', function (err, rows){ if(err){ console.log(String(err).error.bgWhite) ...

I am encountering a situation in which the controller file is returning empty data when logging the contents of req

User Model const mongoose = require("mongoose"); const userSchema = mongoose.Schema( { name: { type: String, required: true }, email: { type: String, unique: true, required: true }, password: { type: String, required: true }, pic: { ...

Using Jquery to target an element within the same DOM element and apply changes

My website platform doesn't assign any IDs or classes to the menus it generates, and uses nested lists for submenus. To make the submenus expand upon clicking, I created a jQuery script: $(function () { $(".wrapper ul li").click(function () { ...

at" symbol used as a parameter indicator in defining resources

According to the information provided in the documentation (http://docs.angularjs.org/api/ngResource.$resource): The syntax for using $resource is as follows: $resource(url[, paramDefaults][, actions]); The optional parameter paramDefaults represents the ...

How can AngularJS handle sorting based on the start date and end date?

Is there a way to filter the items by Start and End Date, based on the invoice_date, using the date range functionality in a meanjs app? I am facing an issue where the date filter functions work perfectly in Plunker and my localHost production environm ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

Bootstrap Tags Input - the tagsinput does not clear values when removed

I am attempting to manually remove the input value from bootstrap-tags-input when the x button is clicked, but the values are not changing in either the array or the inputs. This is the code I have tried: $('input').tagsinput({ allowDuplica ...

Encountering Issues with Discord JS as Member Fetch Returns Undefined

I'm facing an issue with fetching specific server members by their user id in order to assign a role to them. I keep getting an undefined response each time. Even though this bot has administrator permission and all required intents are assigned, I a ...

Obtaining Compiled HTML Output Using AngularJS

I'm running into an issue with obtaining the compiled html of a page in AngularJS. Below is the code snippet that demonstrates this problem: JavaScript: <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script> &l ...

Headers error encountered during sending request

When making a request with this method, an error labeled as "[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client" occurs. I recently started learning about express and might have made some progress. Can you please help me identif ...

When displaying JSON data in an Android app, the ListView is only displaying a single row

I am working on displaying JSON data in a ListView within an Android app. I am able to retrieve the JSON data successfully, but when attempting to display it in the ListView, only one row is showing up. Additionally, I want each row’s data to be shown in ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

Is there a way to cancel an AJAX request during the ajaxStart or ajaxSend event in jQuery?

In my project, I have implemented numerous $.post methods and now I need to check the session in each request to handle my page based on session value. However, I don't want to modify all the existing methods ($.post). Instead, I would like to check t ...

Calculating the quantity of elements within a jQuery array

A JQuery array is proving to be quite problematic. Here's what it looks like, [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32] Unfortunately, there are duplicates present in this array. My goal is to obtain the count of each unique element ...

Refresh my website's specific table automatically whenever the database is updated. Alternatively, reload the table every 2 seconds to ensure the latest values from the database are displayed

How can I update table values in real-time when the database in phpMyAdmin is updated? I have implemented some code that successfully updates the data on my webpage, but the issue is that the entire page reloads every 2 seconds. Is there a way to only ...

Get the top retweeted tweets associated with a specific keyword

There was a discussion on the same topic over at StackOverflow a while back, but unfortunately it didn't get any answers and was specifically focused on hashtags. So, I decided to bring up the question again: I'm interested in finding a way to r ...

Retrieving information from the mainframe

Is there a way to retrieve data from the server using a factory and then return an object that includes this data? The data I need is stored in the directory data/es/20130709.json relative to index.html. This data (20130709.json) is structured like this: ...

Discover the way to retrieve PHP SESSION variable within JavaScript

I'm currently working on developing a platform for image uploads. As part of this project, I assign a unique identifier to each user upon login using $_SESSION['id'] in PHP. Now, I am looking for a way to verify if the $_SESSION['id&apo ...