Why won't my AngularJS checkbox stay checked?

In my application, I have the following code:

      <input type="checkbox" ng-checked="vm.eduToEdit.test" />
      {{vm.eduToEdit.test}}
      <input type="checkbox" ng-model="vm.eduToEdit.test">

The value of vm.eduToEdit.test is displaying true or false, but regardless of the value, the checkboxes in both input fields above remain unchecked. I have tried using ng-model and ng-checked, but none of them seem to work.

EDIT: I also attempted the following without success:

       <input type="checkbox" ng-checked="vm.eduToEdit.test" /> - 
       <input type="checkbox" ng-checked="checking" /> - 
       {{vm.eduToEdit.test}}
       {{checking}}

In my controller, I have:

    vm.eduToEdit.test = true;
    $scope.checking = true;

Although "true" is displayed on the page, the checkboxes are never checked.

Here is my controller:

(function () {
'use strict';

myModule.controller('EducationController', ["$scope", "bootstrappedData", EducationController]);

function EducationController($scope, bootstrappedData) {
    var vm = this;
    vm.shoppingCart = bootstrappedData.shoppingCart;
    vm.eduToEdit = {};

    vm.EditEducation = function (applicantEducationId, educationTypeId) {
        var owl = $(".owl-carousel");

        var eduFound = $.grep(this.shoppingCart, function (h) {
            return h.ApplicantEducationId === applicantEducationId;
        });
        vm.eduToEdit = eduFound[0];
        vm.eduToEdit.formattedAttendEnd = vm.ConvertToDate(vm.eduToEdit.AttendEnd);
        vm.eduToEdit.formattedAttendStart = vm.ConvertToDate(vm.eduToEdit.AttendStart);
        vm.eduToEdit.formattedGraduationDate = vm.ConvertToDate(vm.eduToEdit.GraduationDate);

        vm.eduToEdit.test = true;
        $scope.checking = true;

        switch (educationTypeId) {
            case 1:
            case 2:
            case 3:
            case 4:
                owl.trigger('to.owl.carousel', [1, 50]);
                break;
            case 5:
                owl.trigger('to.owl.carousel', [3, 50]);
                break;
            case 6:
                owl.trigger('to.owl.carousel', [2, 50]);
                break;
            case 7:
                owl.trigger('to.owl.carousel', [4, 50]);
                break;
            case 9:
                owl.trigger('to.owl.carousel', [5, 50]);
                break;
        }
    };

    vm.ConvertToDate = function (jsonDateToConvert) {
        if (jsonDateToConvert == null)
            return "";
        var value = new Date
        (
             parseInt(jsonDateToConvert.replace(/(^.*\()|([+-].*$)/g, ''))
        );
        return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
    }
}

})();

Answer №1

When utilizing ng-checked, it will only display the checkbox as checked or unchecked without affecting the controller variable. If you need to update the controller variable based on changes in the DOM, it is advisable to use ng-model for checking or unchecking. You can try the following:

It seems like you have used controller as vm in the DOM and referenced it with this in the controller.

In HTML:

<body ng-controller="myCtrl as vm">
    <input type="checkbox" ng-model="vm.eduToEdit.test">{{vm.eduToEdit.test}}
</body>

Controller:

angular.module('myApp',[])
.controller("myCtrl", function($scope) {
  var vm = this;
  vm.eduToEdit = {};
  vm.eduToEdit.test = true;
});

DEMO LINK

Answer №2

To update the first checkbox, simply click on the second checkbox. This is because the ng-model is bound to the second checkbox, so any click on it will automatically update the value in the first checkbox.

    <input type="checkbox" ng-checked="vm.test" />
    {{vm.test}}
    <input type="checkbox" ng-model="vm.test" /> 

Check out this jsfiddle link for a demo

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

When attempting to import Quill-blot-formatter with react-quill via next/dynamic, the registration process fails and continues to display a loading message

After creating a function component and configuring quill-blot-formatter with react-quill, I added the blotFormatter to the modules list. Then, I imported this module using next/dynamic on the desired page. The custom function looks like this: import Reac ...

Tips for ensuring the footer always stays at the bottom of the page

I'm having an issue with keeping the footer pinned to the bottom of the page. I haven't applied any specific styles to the footer, just placed it at the end of the content. Everything looks great until there's a page with minimal content, ca ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...

Ways to bring in external javascript files in reactjs

I'm currently working on a form that requires the user to input their location. To achieve this, I have integrated the npm package react-geosuggest-plus. However, I want to avoid including <script src="https://maps.googleapis.com/maps/api/js?key=AI ...

Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table. Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I n ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

passing arguments during deferred resolve() and when() operations

I am currently working on a flash card website and I need to determine the status of preloaded images once they have finished loading or if there was an error. After obtaining the status of each image, I will proceed with further actions. My code is inspi ...

Updating website content dynamically using Javascript and JSON-encoded data

My programming code seems to be acting oddly. I have structured my data in a JSON object as follows: injectJson = { "title": "Champion Challenge Questions", "rules": [ { "idChrono": "chrono-minute", "text": "Top is missing!", ...

Show only specific data from JSON results

I am trying to display a specific cryptocurrency's price without the need for curly braces or explicitly stating "USD". Currently, it appears as {"USD":0.4823} when using the following code: <script> $(document).ready(function () { ...

Troubleshooting: Height setting issue with Kendo UI Grid during editing using Jquery

Issue: My Kendo UI JQuery Grid is fully functional except for a bug that occurs when adding a new record. When I add and save a new record, the grid's footer "floats" halfway up the grid and the scrollbar disappears, making it look distorted. Furth ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

Creating a custom JavaScript library using an existing npm module (codius)

Embarking on a new journey with this, never tried it before. Currently utilizing https://github.com/codius/codius-host. The development of Codiu§ has been abandoned, however I am determined to salvage some parts of it for my own project. It is crucial fo ...

Navigate to the same destination with React Router Dom while passing state as a parameter

Let's talk about a scenario with a Link setup like this: <Link to={`/samelocation/${id}`} state={{ state1: 'hello' }}> This link is nested in a sub-component within the main component situated at /samelocation/:id. To ensure that the ...

Creating a Robust Next.js Build with Tailor-Made Server (Nest.js)

I'm in need of assistance with compiling/building my project using Next.js while utilizing a custom server. Currently, I have integrated Nest.js (a TypeScript Node.js Framework) as the backend and nested Next.js within it. The integration seems to be ...

Using private members to create getter and setter in TypeScript

Recently, I developed a unique auto getter and setter in JavaScript which you can view here. However, I am currently unsure of how to implement this functionality in TypeScript. I am interested in creating an Object Oriented version of this feature if it ...