Angular.js model that is updated by checkboxes

In my project, I have created a model that is linked to several other models. For instance, let's consider a scenario similar to a Stack Overflow question associated with tags. Before making a POST or PUT request, the final Object may appear like this:

{
  id: 28329332,
  title: "checkboxes that append to a model in Angular.js",
  tags: [{
    id: 5678,
    name: "angularjs"
  }, {
    id: 890,
    name: "JavaScript"
  }]
}

The controller I have set up so far looks like this:

.controller('CreateQuestionCtrl',
    function($scope, $location, Question, Tag) {
      $scope.question = new Question();
      $scope.page = 1;
      $scope.getTags = function() {
        Tag.query({ page: $scope.page }, function(data) {
          $scope.tags = data;
        }, function(err) {
          // Handling error when accessing a non-existent page
        })
      };
      $scope.create = function() {
        $scope.question.$save(function(data) {
          $location.path("/question/" + data.id);
        });
      };
      $scope.$watch($scope.page, $scope.getTags);
    }
)

All the available tags are displayed on the page in a paginated manner. The goal is for users to select certain tags and add them to the model for saving.

Is there a way to implement a checkbox interface that updates the $scope.question with the selected tags from other models?


A recent realization suggests progress made towards the solution:

<div class="checkbox" ng-repeat="tag in tags.objects">
  <label><input
    type="checkbox"
    ng-change="setTag(tag.id)"
    ng-model="tag"
  >&nbsp;{{ tag.name }}
</div>

Subsequently, in the controller:

$scope.setTag = function(id) {
  Tag.get({id: id}, function(data) {
    // Further steps required here
  })
}

Answer №1

To reach your goal, you need to follow a specific instruction. Check out the plunker I created for you by visiting this link. In this example, the tags selected are displayed with their respective text property, showing that the object structure is maintained. For your scenario, you should associate the $scope.question.tags array with the collection attribute and each tag from $scope.tags with the element attribute.

Answer №2

Check out this CodePen example featuring multiple checkboxes connected to the same model.

HTML

<html ng-app="codePen" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Multiple Checkboxes</title>
</head>

<body>
  <div ng:controller="MainCtrl">
    <label ng-repeat="tag in model.tags">
        <input type="checkbox" ng-model="tag.enabled" ng-change="onChecked()"> {{tag.name}} 
    </label>
    <p>tags: {{model.tags}}</p>
    <p> checkCount: {{counter}}  </p>
</body>
</html>

JavaScript (JS)

var app = angular.module('codePen', []);    
    app.controller('MainCtrl', function($scope){
        $scope.model = { id: 28329332,
        title: "Dynamic Checkbox Binding Using Angular.js",
        tags: [{
          id: 5678,
          name: "angularjs",
          enabled: false
        }, {
          id: 890,
          name: "JavaScript",
          enabled: true
        }]
        };
      $scope.counter = 0;
      $scope.onChecked = function (){
        $scope.counter++;
      };
 });

Answer №3

While searching for solutions, I came across a useful library known as checklist-model. It provided a straightforward approach to implementing checkboxes in Angular. Here is a snippet of the code I used:

<div class="checkbox" ng-repeat="tag in tags">
  <label>
    <input type="checkbox" checklist-model="question.tags" checklist-value="tags"> {{ tag.name }}
  </label>
</div>

This information was discovered through a simple search on "directives for angular checkbox".

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 validate a template-driven form without using the model-driven approach?

Attempting to validate a template-driven form in Angular without two-way data binding has proved to be challenging. I have successfully implemented validation using [(ngModel)], but running into an error when trying to validate the form without the MODEL p ...

Having trouble with a Vue3 project after running a Vite build in production mode?

When I run my project in development mode, everything works perfectly fine. However, when I build the project using `vite build´, some components stop functioning. Oddly enough, there are no errors displayed in the console or in the build logs. If I use ...

Generating a new root in React 18 results in numerous rounds of rendering and execution

Every time I attempt to run this code in React 18, it seems to render multiple times unlike React 17 where it only executes once and functions properly. How can I modify the code so that it only runs once? Is there a specific reason for the multiple execu ...

Connecting nodes to edges based on their unique ids in the d3.js graph library

I am encountering an issue with this code while trying to integrate it with a new JSON object called 'new_json'. Specifically, I need the links in this code to be created based on the nodes' IDs. Can anyone provide assistance with this? va ...

The Jquery script is ineffective for newly added elements

After creating an Ajax Form that functions well, I noticed that when the result of the form is another form, my script does not work for the new form generated. Is there a way to make the new form function like the old one? $(document).ready(function() ...

Getting the most out of option select in AngularJS by utilizing ng-options

I'm currently working with AngularJS and I am interested in utilizing ng-options for a select tag to showcase options organized under optgroups. Here is the array that I intend to use in my select option: $scope.myList = [ { "codeGroupComp ...

What are the differences between displaying JSON data on a Flask interface compared to a Django interface

Currently, I am looking for the simplest method to display data on a web interface using either Flask or Django (whichever is easier). I already have some sample JSON objects available. Could anyone provide recommendations on how to achieve this and whic ...

An error known as "cart-confirmation" has been encountered within the Snipcart platform

I am looking to integrate Snipcart checkout in my Next.js application. However, when I try to validate a payment, I encounter an error message: An error occurred in Snipcart: 'product-crawling-failed' --- Item 1 --- [Item ID] 8 [Item Unique ID] ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

Generating a 3D face using three coordinates in Three.js

Currently, I have implemented code that allows me to load, render, and display a STL object using Vue.js and Three.js. My goal now is to replace the currently selected plane with a new face. I've managed to extract the 3 vertices of the clicked-on fac ...

When a JSON object is handled as a string

The JSON returned from my Ajax call looks like this: returnedData = "[ { id: 1, firstName: 'John', lastName: 'Smith', address: '123 Spa Road', city: 'London', orders: [ { product: ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

"Troubleshooting: Why isn't AngularJS $http.post sending my data

Feeling frustrated with my experience using AngularJS and Laravel 5.2. I'm trying to make a standard $http post request: APIservice.saveArticle = function ( oArticle, callback ) { var message = 'Hello World!'; $http({ metho ...

Tips for properly implementing a bcrypt comparison within a promise?

Previously, my code was functioning correctly. However, it now seems to be broken for some unknown reason. I am using MariaDB as my database and attempting to compare passwords. Unfortunately, I keep encountering an error that says "Unexpected Identifier o ...

Merging Angular with jQuery: Organizing jQuery into a distinct file leads to the error message 'Property 'top' cannot be read because it is undefined.'

My project is based on AngularJS, and I've been trying to incorporate a jQuery code for a sticky sidebar feature. Strangely enough, when I tested my code on Plunkr, it works perfectly fine. However, when I try to implement it in my actual project, it ...

Guide to changing the checkbox value using JavaScript

Describing the Parent Element: <span style="background: yellow; padding: 50px;" onClick="setCheckBox()"> <span> </span> <input type="checkbox" name="f01" value="100"> </span> ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

Leverage PHP to integrate JSON data for consumption by JavaScript

I've been exploring the integration of React (JavaScript) within a WordPress plugin, but I need to fetch some data from the database for my plugin. While I could retrieve this data in JavaScript using jQuery or an API call, because the data will remai ...

Tips for managing nested objects within React state and keeping them updated

Could someone kindly point out where I might be going wrong with this code? Upon checking the console.log, it seems like the date function is functioning correctly. However, despite using this.setState, the timestamp remains unchanged. Any help would be gr ...