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

Protecting Against Cross-site Scripting (XSS) Attacks in AngularJS and WebAPI

Looking for assistance in preventing XSS attacks in my project which utilizes (AngularJS and Web API) and complies with OWASP guidelines. Currently, ngsanitize is successfully preventing script injection from the UI, however, I have identified a vulnerabil ...

Utilizing Selenium and BeautifulSoup to extract data from a website

I am currently in the process of scraping a website that dynamically loads content using JavaScript. My objective is to create a Python script that can visit a site, search for a specific word, and then send me an email if that word is present. Although I ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

Steps to initiate a slideUp animation on a div using jQuery

Is there a way to make a div slide up from the bottom of the page to cover 30% of the screen when a user clicks a button, and then slide back down when the button is clicked again? Any suggestions on how I can achieve this? Thank you! EDIT 1) $(document ...

Activate a button with jQuery when a key is pressed

Currently, I have two buttons set up with jQuery: $('#prev').click(function() { // code for previous button }); $('#next').click(function() { // code for next button }); My goal now is to implement a .keypress() handler on the ...

Issue encountered while executing npm command: "Module 'npmlog' not found"

Today marks the beginning of my first job, and as I was setting up my development environment on my Mac (OSX) by updating node and npm, something went awry. Whenever I attempt to use npm in my command line (npm init, npm install, etc.), I am confronted wit ...

Guidance that utilizes the scope of a specific instance

I have successfully created a d3.js directive, but I am facing an issue when resizing the window. The values of my first directive seem to be taking on the values of my second directive. How can I separate the two in order to resize them correctly? (both ...

Attempting to compare the HTML datetime with the current time in order to implement conditional formatting

I am working with a SharePoint discussion list that includes a field named "Last Updated." My goal is to identify and highlight rows where the last update was more than 1 hour ago. Here is my current approach: <html> <head> <sc ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

Sending JSON data containing special characters from AngularJS to Ruby server

I am currently working on creating a search form that utilizes Ruby for the back end and Angular for the front end. The search query is constructed in Angular in JSON format and then sent to Ruby through a RESTangular service. Everything was functioning c ...

I'm encountering an issue where the this.props object is undefined even though I've passed actions to mapDispatchToProps. What could

Summary: The issue I'm facing is that in the LoginForm component, this.props is showing as undefined even though I have passed actions in mapDispatchToProps. I've debugged by setting breakpoints in the connect function and confirmed that the act ...

Using Capybara for testing integration with asynchronous JavaScript

I am currently facing an issue with a failing Rails integration test that has me stumped. The test utilizes Capybara with Selenium as the driver. The specific problem lies in verifying that certain page content is removed after an AJAX call is made. Essen ...

The x-axis is represented by JSON keys, while the y-axis is represented by

I am currently attempting to replicate a graph that was originally made in Excel. Here is the code I have written so far: var data = [ { 'FB':4, 'Mv':4, 'CB':5, 'SL':3, ...

How can JavaScript be used to automatically send a user to a designated page based on a selected option in

I am in the process of creating a JavaScript function that redirects users based on their selection from a dropdown menu. Additionally, I need to ensure that the word "admin" is set for both the username and password fields. view image here function my ...

JavaScript's failure to properly handle UTF-8 encoding

Here is a snippet of code that I found on Stack Overflow and modified: <?php header('Content-Type: text/html; charset=ISO-8859-1'); $origadd = $_SESSION["OriginAdd"] // $_SESSION["OriginAdd"] contains the value "rueFrédéricMistral"; echo $o ...

Having difficulty manually concealing the launch image on the physical device

When testing my trigger.io app on the Android simulator or my Nexus phone, I can manually hide the launch image through code successfully. However, when running the app on the iOS simulator, the launch image remains visible. Additionally, when debugging di ...

When utilizing useEffect in Next.js, an error may occur stating that the window is

It seems like there is a challenge with executing script code server side in next.js 13 when it needs to be executed client side. Currently, I am trying to implement the bulma calendar found at When importing the required library: import PasswordStrengthB ...

Effective and Sustainable Methods for Error Management in Node/Express API Endpoints

Throughout my experience with developing MEAN Stack applications and setting up APIs, I have encountered some uncertainty when it comes to handling errors within API Routes. If there are any inaccuracies in my explanation or if my concepts are flawed, ple ...

Is it possible to utilize ember-cli solely as a frontend tool, much like how we use JavaScript and jQuery?

Is it feasible to employ ember-cli exclusively as a front-end tool, similar to utilizing JavaScript and jQuery? I am interested in incorporating a reference to ember-cli in my .NET project solely for validation purposes. Is this a viable approach, and an ...

Managing and retrieving data in bulk from an indexed database as JSON format

I am currently developing an application that utilizes IndexexDB for local data storage. I am looking for a way to extract and insert large amounts of data from an indexed DB in JSON format. Below is the code snippet illustrating what I have accomplished s ...