Angular Checkbox Binding Issue Detected

Struggling with a problem related to an Angular checkbox form that is generated from an API.

I am able to create checkboxes, but encountering two issues: The checked state of the boxes does not align with the values retrieved from the API, and when I click on the checkboxes, the name value changes from its default to "true" or "false." Despite looking at similar questions, I have been unable to resolve this issue. You can find the Plunk here along with the corresponding source code below:

<!doctype html>
<html ng-app="checkTest">
    <head>
        <meta charset="utf-8">
        <title>Angular Multiple Checkboxes</title>
        <style>
            label {display:block;}
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
        <script type="text/javaScript">
        var jsonObj = {"fruits":[
            {
              "name": "Apple",
              "desc": "abcdefg",
              "selected": "true",
              "status": "Created"
            },
            {
              "name": "Broccoli",
              "desc": "abcdefg",
              "selected": "true",
              "status": "None"
            },
            {
              "name": "Cucumber",
              "desc": "abcdefg",
              "selected": "false",
              "status": "Created"
            },
            {
              "name": "Daikon",
              "desc": "abcdefg",
              "selected": "false",
              "status": "None"
            }
      ]};
            var fruitsObj = jsonObj.fruits;
        </script>

    </head>

    <body>
        <div ng-controller="MainCtrl">

            <label ng-repeat="fruit in fruits">
                <input type="checkbox" name="fruitSelect" ng-model="fruit.name" ng-value="{{fruit.name}}" ng-checked="fruit.selected"> {{fruit.name}}
            </label>
            <p>Services: {{fruits}}</p>
        </div>

        <script type="text/javaScript">

            var app = angular.module('checkTest', []);

            app.controller('MainCtrl', function($scope) {
                $scope.fruits = fruitsObj;
            });

        </script>
    </body>
</html>

Answer №1

Make sure to use booleans as either true or false, rather than as strings like 'true' or 'false'

Furthermore, the ng-checked directive is unnecessary. Instead, include {{index}} in the form field to create a unique element within the form, such as serviceSelect-{{$index}}

Markup

<input 
    type="checkbox" 
    name="serviceSelect-{{$index}}" 
    ng-model="fruit.selected" 
    ng-value="{{fruit.name}}" /> 

Check out the Demo Plunkr

Answer №2

Angular checkbox values can be either true or false. To implement this, use the following code:

<input type="checkbox" name="serviceSelect" ng-model="fruit.selected" ng-value="{{fruit.name}}" ng-checked="fruit.selected">

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

Retrieve and utilize the dynamically produced values from the application's app.js in a script that is accessed using

In my Express.js Node web app, I generate a string in app.js during initialization: // app.js var mongourl = /* generated based on process.env.VCAP_SERVICES constant */; There is a script that I import into app.js using require(): // app.js var db = req ...

Animate an svg icon to follow a designated path as the user scrolls

I am currently working on a project that involves animating a bee svg icon as the user scrolls through the website. The bee starts at the top and fills in a grey color line with pink as the user moves forward, and moves backward as the user scrolls back. Y ...

Using database entries to generate dynamic routes in express.js without the need for a server restart

I have created a custom Express instance for my KeystoneJS v5 app that serves data stored in a Postgres database with the following model: CREATE TABLE "Link" ( id integer DEFAULT PRIMARY KEY, customer text, slug text ); I've set up dyna ...

Receiving the error "Potential null object. TS2531" while working with a form input field

I am currently working on developing a straightforward form to collect email and password details from new users signing up on Firebase. I am utilizing React with Typescript, and encountering an error labeled "Object is possibly 'null'. TS2531" s ...

Multiple button clicks causing events to fire repeatedly

My PHP file echoes a button, but when I click it, the action fires multiple times. Why is it behaving like this? I have tried solutions from Stack Overflow, but none of them seem to work. Any suggestions or corrections? $(document).on('click',& ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

What is the best way to swap out elements in my string with those from an array?

Struggling to replace special characters in file names before saving them to the Windows filesystem due to compatibility issues. For my initial approach, I used the replace() method repeatedly on the string to replace specific special characters. Here&apo ...

Adding TypeScript types to an array within a function parameter: A step-by-step guide

Having some trouble defining the array type: The code below is functioning perfectly: const messageCustomStyles: Array<keyof IAlertMessage> = [ 'font', 'margin', 'padding' ]; r ...

Troubleshooting Bootstrap select box design discrepancies

Currently revamping a website and encountered an unusual issue with select boxes. There seems to be an overlapping white space where the option values should be. Here's a visual reference: View Image of Select Box Issue Utilizing Bootstrap for the re ...

What is the most effective method of utilizing union or extend in TypeScript when faced with a comparable scenario?

I have a function that takes in two different types of objects: const canBeGenericOrDefaultData = { id: 123, pointData: { square: 'x145', triangle: 'y145' } } function submitHandler(canBeGenericOrDefaultData: AllTheDatas | G ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

Choose to conceal beneath the table within Bootstrap 4

As a budding web developer, I am currently using Bootstrap 4 in my project. If you take a look at my preview by clicking here and then selecting "Liczba sztuk," you'll notice that I am facing an issue. The items within the select dropdown are gettin ...

The issue with MUI material autocomplete not functioning properly when onBlur is triggered

Although the onFocus parameter is working fine in material autocomplete, I'm facing an issue with the onBlur parameter. Can someone explain why this might be happening and provide a correct solution to implement it? <Autocomplete onBlur={() ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

Click the button in Javascript to add new content

I am currently experimenting with JavaScript to dynamically add new content upon clicking a button. Although I have successfully implemented the JavaScript code to work when the button is clicked once, I would like it to produce a new 'hello world&ap ...

site.js problem

Recently, I decided to create my very own CS:GO gambling website. After successfully setting it up on my localhost using VPS, I moved on to getting a domain and finalizing everything. However, when attempting to run site.js, an error message popped up: [e ...

Booting up the node.js environment with the help of a C++ application

Is it possible to start Node.js from a C++ application? The reason I ask is because I have a C++ console application that launches a JavaScript application which uses require('os'). However, it is failing with the error "Uncaught ReferenceError: ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

Using PHP to iterate through an array and output the values within a

Hey there! I have a question about incorporating PHP foreach and echo into JavaScript to make it dynamic. Here is the current static JavaScript code: <script type="text/javascript"> $(document).ready(function(){ $('input[type="checkbox"]&ap ...

Unlocking the power of $http convenience shortcuts in AngularJS

I have developed a custom function (credit to source) that wraps an AngularJS $http function in a way that switches between browser XHR and cordova-plugin-advanced-http based on the device platform. While the function works seamlessly with $http({method:& ...