Mastering the concept of accessing checkbox values in AngularJS using ng-repeat

Just starting out with Angular so bear with me :)

I'm working on a page that displays a list of items from a JSON object. This JSON object contains an array of dates.

$obj = [
    {
        id: '1',
        GoalName: 'Drink More Water',
        StartDate: '9/1/2015',
        EndDate: '9/30/2015',
        GoalType: "positive",
        Category: "Health",
        Weight: "3",
        TimesPerWeek: 4,
        Dates: {
            "09/11/2015": 0,
            "09/10/2015": 1,
            "09/08/2015": 1
        }
    }

I've managed to use ng-repeat to display the items from the array, but I'm struggling with controlling the checkboxes. What I want to do is display a date on the screen and then check if that date is present in the array, and if it is, mark the checkbox as checked. Additionally, when a user clicks the checkbox, it should update the item. I know I need to create a model for the checkboxes, but I'm not completely sure how to go about doing that.

app.controller('TrackGoals', function ($scope) {
    $scope.today = Date.today();
});

<ul class="list" id="thehabits" ng-repeat="goal in goals">
    <li class="expanded-cell">
        <div class="pull-right form-group cell-content">
            <label>
                <input type="checkbox" class="option-input checkbox" ng-model="ids[goal.dates.id].value">
            </label>
        </div>
        <div class="cell-content">
            <span id="habittext" class="title">{{ goal.GoalName }} </span>
        </div>
    </li>
</ul>

Answer №1

Give this a try:

var app = angular.module('myApp', []);
app.controller('TrackGoals', function($scope) {
  $scope.goals = [{
    id: '1',
    GoalName: 'Eat Healthier',
    StartDate: '11/1/2015',
    EndDate: '11/30/2015',
    GoalType: "positive",
    Category: "Health",
    Weight: "3",
    TimesPerWeek: 4,
    Dates: {
      "11/11/2015": 0,
      "11/10/2015": 1,
      "11/08/2015": 1
    }
  }, {
    id: '2',
    GoalName: 'Exercise More',
    StartDate: '11/1/2015',
    EndDate: '11/30/2015',
    GoalType: "positive",
    Category: "Fitness",
    Weight: "3",
    TimesPerWeek: 4,
    Dates: {}
  }];
  $scope.setCheckboxVal = function(val) {
    var arr = [];
    for (var i in val) {
      if (val.hasOwnProperty(i)) {
        arr.push({
          date: i,
          value: val[i]
        });
      }
    }
    return !!arr.length;
  };
  $scope.showData = function() {
    console.log(JSON.stringify($scope.goals));
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app='myApp'>

<head>
  <meta charset="UTF-8">
  <title>Test</title>
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="angular.min.js"></script>
</head>

<body ng-controller="TrackGoals">
  <ul class="list" id="thehabits" ng-repeat="goal in goals">
    <li class="expanded-cell">
      <div class="pull-right form-group cell-content">
        <label>
          <input type="checkbox" class="option-input checkbox" ng-model="goal.checkboxVal" ng-init="goal.checkboxVal=setCheckboxVal(goal.Dates)">
        </label>
      </div>
      <div class="cell-content">
        <span id="habittext" class="title">{{ goal.GoalName }} </span>
      </div>
    </li>
  </ul>
  <button type="button" ng-click="showData()">Show data</button>
</body>

</html>

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

CSS - starting fresh with animations

I am facing an issue with a CSS animation that I created. Everything seems to be working correctly, but I need to complete it by setting the input type to reset the animation. Below is the CSS code snippet that should reset the animation: $('button& ...

If I am already in the child router and attempt to refresh the browser, I will not be able to load

This is a custom router configuration for student enrollment. var studentEnroll = { name: 'student-enrollment', label: "Enroll Student", url: '^/home/students/enroll', par ...

extracting attributes from JSON using Python

When making a call to a URL that returns a JSON object with an attribute labeled from, I attempted to access it in Python using the following code: object.from.username $ python sample_app.py File "sample_app.py", line 63 print comment.from.usern ...

Utilizing a custom adapter for a ListView in an Android application

I am currently transitioning from using a Regular listview that handles JSON responses to utilizing a listview with Fragments using JSON data and the Sherlock library Progress so far:: Successfully imported the Sherlock library into my project Convertin ...

What is the best way to assign a JavaScript return value to a PHP variable?

Is it possible to capture the return value of a JavaScript function that checks if text boxes are empty and assign it to a PHP variable? I have successfully created a JavaScript function that returns false if any of the text boxes are empty, but now I ne ...

Dynamically linking tabbable tabs is a useful technique that allows for

I have been working on an app that organizes websites into groups displayed as tabs in a tabbable navigator using Twitter Bootstrap. The idea is that each time a new group is added, a new tab should appear. Currently, this is how it looks: The functionali ...

Experiencing difficulties integrating Python Requests with the Bonanza API in Node.js due to a lack of proper documentation and inability to make successful API

I've been following the Bonanza.com Bonapitit documentation and managed to make their Python fetchToken script work. However, I'm now attempting to replicate this script in Node.js for my ExpressJS backend instead of using Python. Here's ho ...

Storing information using JSON within a specialized class

I'm struggling to grasp the concept of ajax. I've been attempting to save the Patient object from JavaScript to the server-side database, but the code provided consistently triggers an [alert("error")]. Could someone please help me identify the ...

The function HandleKeyPress is failing to recognize the input from the down arrow

I'm currently working on developing a customized and user-friendly select input using React.js. My goal is to have the functionality where the up and down arrow keys behave like the tab key within the context of selecting options. In order to achieve ...

Implementing setTimeout with the copy button: A guide

How can I implement a setTimeout function in the copy button so that when a user clicks on it, the text will change to "copied" and then revert back to "copy" after 3-4 seconds? Please help me find a solution to this problem and also optimize the JavaScrip ...

Is it necessary to confirm the validity of url.format(urlObject)?

I have been exploring the NodeJS URL API and am particularly interested in the url.format(urlObject) method. My goal is to develop a function that first validates the urlObject before using the format function, and throws a TypeError if any of the key/valu ...

Enhancing the styling of checkboxes using CSS and Javascript

My Javascript skills have been put to the test with a simple code snippet that customizes checkboxes by hiding them and using background images in CSS to display checks and unchecks. It's a neat trick, but I'm wondering if it's HTML/CSS comp ...

JavaScript file creation and opening issue in Firefox

Check out my code snippet below: var blob = new Blob([data], { type: 'text/plain' }); var downloadLink = angular.element('<a></a>'); downloadLink.attr('href', window.URL.createObjectURL(blob)); downloadLink.attr ...

The v-data-table fails to refresh with new data

Within my Vuex store, I have an object called portfoliosData which contains a property named metrics. state: { portfoliosData: { performance: [], metrics: [] }, When I trigger an action, I update the property in the store and aim to ...

Making a jQuery post request that returns JSON data

Is it possible to use the jQuery $.ajax method for making a POST request and sending data (e.g. page.aspx?var1=value) while also specifying that the expected response from the service will be in JSON format? var data = {name: _name, ...}; var request = $ ...

"Ensure only one checkbox is selected at a time by unchecking the previous

Hi, I'm facing two issues with the code below. The first problem is that when I select checkbox number 3, it automatically selects number 2 as well. I only want this to happen if I manually check it (similar to checkbox number 2). The second issue i ...

Generating an image in Fabric.js on a Node server following the retrieval of canvas data from a JSON

I've been trying to solve this problem for the past few days. In my app, users can upload two images, with one overlaying the other. Once they position the images and click a button, the canvas is converted to JSON format and sent to a node (express) ...

"Receiving data from an axios call in React using useEffect leads to an error message: "Property 'numero' cannot be read as undefined"

I am encountering an issue while trying to fetch a mock API using axios. Setting up the useEffect hook to fetch the API data const FetchMockAPI = () => { const [data, setData] = useState(); useEffect(() => { ...

Setting a default string value for a null JSONObject

I am successfully passing data to a recycler view using JSON, but I am facing a specific issue. The problem arises when the user does not upload a profile image, resulting in the database field for image being blank and the JSON not parsing any data for i ...

Include a link to a JavaScript file within a dynamically created HTML page in a Delphi VCL application

I am currently developing a Delphi XE5 VCL Forms Application which includes a TIdHTTPServer on the main form. Within this server, there is a CommandGet procedure called IdHTTPServer: procedure TForm1.IdHTTPServerCommandGet(AContext: TIdContext; ARequest ...