Learn the method for automatically checking a checkbox when a page is loaded in Angular

I have multiple checkboxes on a single page

<div class="check-outer">
    <label>Place of operation</label>
    <div class="checkDiv">
        <div ng-repeat="place in places">
            <div class="checkbox-wrapper">
                <label> 
                    <input type="checkbox" ng-model="placesOBJ[place.place_id]">
                    <span></span>
                </label>
            </div>
            <label class="chk-lbl">{{place.place_name}}</label>
        </div>
    </div>
</div>

Everything is working as expected. If there is data available, I want the checkboxes to be checked by default

if($scope.client.client_places){
    var plcLength = $scope.client.client_places.length;
    var client_places = new Array();
    for(var i = 0; i < plcLength; i++){
        client_places[i] = $scope.client.client_places[i]['place_id'];
    }
    // console.log(client_places);
    //$scope.placesOBJ4 = client_places;
    $scope.placesOBJ = client_places;
}

The client places array looks like {1, 2}

However, I am facing some issues. If anyone has a solution, please help me out.

Answer №1

Utilize the ng-checked directive by incorporating an expression that aligns with the model

Answer №2

To accomplish your goal, you can utilize the ng-checked directive

<input type="checkbox" ng-model="placesOBJ[place.place_id]" ng-checked="placesOBJ">

When $scope.placesOBJ has data (not null), the condition evaluates to true, and the checkbox will be checked

Answer №3

Take a look at this straightforward code snippet. It could prove to be quite beneficial for you.

<body ng-app="myApp" ng-controller="HomeCtrl" ng-init="init()">

    <div>
          <label>Location</label>

                    <div ng-repeat="place in places" ng-show="check">
                          <input type="checkbox" ng-model="placesOBJ[place.id]" ng-checked="true">
                          <label class="chk-lbl">{{place.name}}</label>
                    </div>

    </div>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script>

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

    app.controller('HomeCtrl', ['$scope',  function($scope) {

        $scope.check=false;
        $scope.places=[{'id':1, 'name':'location1'},{'id':2, 'name':'location2'},{'id':3, 'name':'location3'},{'id':4, 'name':'location4'}];

        $scope.init=function()
        {
            if($scope.places)
            {
                $scope.check=true;
            }
        }

    }]);

  </script>
</body>

Explanation:- Utilize ng-init="init()" to trigger on page load. It will verify the presence of data. If data is present, ng-show="true" is set, otherwise it defaults to false.

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

Working with Ruby on Rails by editing a section of embedded Ruby code in a .js.erb file

Currently, I am in the process of developing a single-page website and have successfully implemented ajax loading of templates to insert into the main content section. However, I am encountering difficulties when trying to do this with multiple templates u ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...

centering an angular material card on the webpage

Currently, I have developed a Registration script that enables users to Sign Up on my website. However, the issue I am facing is that the angular material card, which houses the sign up interface, is not centered. Despite trying various methods such as & ...

Koa and Stripe are patiently holding off on displaying the page

My current setup involves using koa and stripe for processing a one-time payment. Although the functionality is there, I'm facing an issue where the page renders before the 'data' assignment takes place. This results in the 'id' sh ...

Issue encountered while validating password using regex pattern?

There seems to be an issue with password validation when requiring 1 upper case, 1 lower case, 1 number, and 1 special character. methods: { validateBeforeSubmit() { this.$validator.localize('en', dict) this.$validator.validate ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

Deleting parentheses within a NodeJS string

I am working with a variable in Nodejs that contains data within square brackets. My goal is to remove the square brackets and extract the actual value from it let value = "[dfsdf][dsfsd][sdfs]MY VALUE"; The value I need to retrieve from the var ...

Concealing the value of the variable within the state function

CODE USED: /*Code snippet from another page with specific URL*/ .state("main/handler/location/userSso",{ url:"/main/handler/:location/:", templateUrl:"component/common/main.html", controller: 'MainContro ...

Troubleshooting JQuery Variable Overwriting Problem

Here is the code snippet I am working with: <script> $(document).ready(function() { var settings_image ={ url:"<?php echo site_url('/cms/editor/upload/images');?>", method: "POST", fileName: "file", returnType: ...

What is the most efficient way to retrieve a substantial volume of data from Mongodb quickly, especially when the query results require processing before transmitting to the client?

My project involves a large Mongodb database paired with a React front-end and Node back-end, housing around 100000 documents. Indexing has been completed and Redis is already in use. The search feature implemented allows users to find relevant documents b ...

Is it possible for an object to receive notifications when a component object undergoes changes in Angular 2/4?

When working with Angular components, it's possible to pass a variable or object as @Input(). The component will be notified whenever the value of this input changes, which is pretty cool... I'm currently developing an application that features ...

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...

Enhancing Bootstrap modals with dynamic content and integrating Ajax for dynamic data retrieval in Laravel

I am facing some challenges while coding in Laravel, specifically with passing data to a modal (using the Bootstrap framework) and sending data to an Ajax post request. I have an array of items with an 'id', a 'name', and 'content& ...

Issues with connecting to Socket.IO in Cordova app

I'm having troubles setting up my Cordova app to establish a socket.io websocket connection. Despite following the instructions I found, it doesn't seem to connect when running in debug mode. Can anyone help me troubleshoot this issue? Server Si ...

Deactivate radio buttons when the table value is greater than or equal to one

On my webpage, there are radio buttons for 'Yes' and 'No'. When 'Yes' is selected, a hidden <div> appears where users can fill in fields. Upon clicking the 'Add' button, the information is displayed in a table. ...

There was an issue with the JSON parsing process due to an unexpected token 'o' at position

Trying to extract titles from a JSON object for a specific feature, here's an example of the JSON structure: [ { "title": "Example 1", "url": "http:\/\/www.example1.com\/" }, { "title": "Example 2", "url": "http:& ...

Transfer information(text) to the clipboard using Vue (Nuxt js)

When the vs-button is clicked, I want the value of single_download_link.pdfId to be copied to the clipboard. I attempted it like this, but it did not work. I do not want to use the v-clipboard node module. Can someone please assist me with this? Thank you. ...

Accessing a PHP variable within an AJAX handling script

Upon user login, the email is stored in $email (I also tried global $email). Subsequently, a form allows the user to input their roommate's name to search for existing appointments. Incorporating AJAX $("#reserveAPickupAppointmentForm3").submit (fun ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

Angularjs: Patience is key as we let the watchers do their magic

Can I delay the execution of my task until a watcher has finished? If so, is there a way to check if the watcher is still running? ...