Tips on how to indicate a checkbox as selected within an Angular controller

I'm in the process of creating a form for entering new service requests, as well as displaying and editing existing ones. One part of this form includes a list of labeled check-boxes that represent different countries. When an existing request is displayed using this form, I need to compare each country check-box with a list of initially selected countries and mark each match as "checked." In other words, I need to restore the state of the check-box list to reflect what was originally checked. Should I handle this type of logic in the controller by iterating over two nested loops (all countries vs. selected countries), or is there a more efficient way to accomplish this using directives?

Here is the check-box list:

<div class="form-group">
                        <label for="selectbasic">What country is the data for</label>
                        <div>
                            <div style='height:100px;overflow-y:auto;border:solid 1px #aaa;'>
                                <div ng-repeat="item in countries">
                                    <input type='checkbox' ng-model="item.checked" ng-change="checkit()" />&nbsp;&nbsp; {{item.name}}
                                </div>

                            </div>
                        </div>
                    </div>

And here is a snippet from my controller where I can possibly address this issue:

function getServiceRequestById(Id) {
            dataFactory.getServiceRequestById(Id)
                .success(function (request) {
                    // Code to set scope variables here

                    var list = [];

                    var countries = request.SelectedCountries.split(',');

                    console.log('Number of countries: ' + countries.length);

                    console.log('Selected countries: ' + countries[0] + ' --- ' + countries[1]);

                    $scope.checkit = function () {

                        for (var p in $scope.countries) {
                            if ($scope.countries[p].checked) {
                                list.push($scope.countries[p].name);

                                console.log("Selected country: " + $scope.countries[p].name);
                            }
                        } return list;
                    }
                    console.log('EditServiceRequestCtrl Request : ' + request);

                })
                .error(function (error) {
                    console.log('getServiceRequestById returned error');
                });
        }

Answer №1

Consider implementing the following approach:

function fetchRequestById(Id) {
  dataAccess.fetchRequestById(Id)
        .done(function (requestData) {
             $scope.data = requestData;
             $scope.selectedCountries = []; //remember to reset selections
             $scope.countries = requestData.SelectedLocations.split(',');
        });
}

$scope.updateSelectedCountries = function() {
    var selectedList = [];
    angular.forEach($scope.countries, function(location) {
       if(location.selected) selectedList.push(location);
    });
    $scope.selectedCountries = selectedList;
};

Next, update your view with the following code:

<div ng-repeat="location in countries track by $index">
    <input type="checkbox" ng-model="location.selected" ng-change="updateSelectedCountries()"/>
</div>

<h4>Output Preview"</h4>
<pre>{{ selectedCountries | json}}</pre>

Answer №2

It appears that you are retrieving a list of countries, each with a "checked" attribute.

My assumption is that you want to display all countries, regardless of their checked status.

If so, the solution is straightforward:

   <div ng-repeat="item in countries">
        <input type='checkbox' ng-model="item.checked"  /> {{item.name}}
    </div>


  $scope.countries = [ {name: "USA", checked: true},
                       {name: "GBR", checked: false},
                       {name: "GER", checked: true}];

Check out a functional example here.

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

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

A script in PHP or JavaScript that dynamically generates two dual drop-down menus to assist with data selection

I have experience with php scripting, but I am facing challenges when trying to combine it with JavaScript. The issue arises when I have a form that includes dropdown menus for categories and subcategories. When a category is selected, the options in the s ...

Sorting through names within a nested array based on specific criteria

I have been struggling to filter by item name for the past day and haven't been successful. The issue lies in my attempt to use a sample array for filtering. While I am able to filter by category successfully, the same cannot be said for filtering by ...

A collection of functions embedded within a JSON data structure

I am working with a website that provides data in a JSON-like format similar to the following: { "name":"tom jones", "no": 123, "storedproc": function(){ callbuyer(0123); } } Currently, I am using $. ...

Error in Google reCaptcha 2: "a is null" occurs when grecaptcha.reset function is executed

I am currently working on a registration page that utilizes AJAX for validation on both the client and server sides. If the server side validation fails, the AJAX function returns the errors to the screen and tries to reset the reCAPTCHA using grecaptcha. ...

Utilizing an Office App Ajax that includes an authentication header, the application connects to a secure Web API 2 backend with CORS

I am currently in the process of developing a content panel application for Office. As part of this project, I need to authenticate an account against a server. To accomplish this, I have implemented my own AuthorizationFilterAttribute on my web api 2 con ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

Inquiry regarding the ng-disabled directive in AngularJS

<div ng-app="myApp" ng-controller="myCtrl"> <button type="submit" class="btn btn-primary pull-left" ng- disabled="captchaError">Submit</button> </div> <script> var app = angular.module('myApp', []); app.controller( ...

Generating a list of objects from an array of strings

I am currently facing an issue in my code and I could use some help with it. Below are the details: I have a array of string values containing MAC addresses and constant min & max values. My goal is to map over these MAC values and create an array of obje ...

Using "array_agg" in a "having clause" with Sequelize

I am facing a particular scenario with my database setup. I have three tables named computers, flags, and computerFlags that establish relationships between them. The structure of the computerFlags table is as follows: computerName | flagId computer1 | ...

What is the best way to retrieve EXIF data following the AJAX loading of images?

Currently, I am developing a swipe-able wine image viewer for NapaWapa.com and it's functioning quite smoothly: The challenge I'm facing is related to using a jquery plugin to extract the exif data from the images in the gallery. Unfortunately, ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...

Unending cycle when integrating AngularJS with Laravel

I am struggling with an issue while integrating ngRoute with Laravel framework. Within my routes.php file: App::missing(function($exception) { return File::get(public_path() . '/angular.html'); }); This is the content of my angular.html fi ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

Accessing a JSON string correctly using JavascriptSerializer in JavaScript

When working with JavaScript, I encountered an issue where the data retrieved from a data table and converted to javascriptSerializer was not refreshing correctly when changing dataset selection parameters. The problem occurred when trying to populate a ne ...

Disregard the popstate triggered by Safari's Initial Page Load

Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...

How can I position 7 images absolutely within a specific div?

I've been working on a website where users can have their avatars displayed using a JS function that loads 7 different images onto the page. These images correspond to different elements such as skin base, hair, eyes, mouth, shirt, shoes, and pants, a ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

Display a series of messages using an Angular directive

Here is a sample HTML code: <section class="correspondence"> <header> <div class="from">{{ message.from }}</div> <div class="when">{{ message.when }}</div> </header> <div class="content"> { ...