Creating a checkbox with AngularJS

My attempt at creating a checkBox using AngularJS led me to this code snippet: http://jsfiddle.net/t7kr8/211/.

After following the steps outlined in the code, my implementation looked like this:

JS File:

'use strict';

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

    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/Carto', {
            templateUrl: 'Carto/carto.html',
            controller: 'CartoCtrl'
        });
    }])

app.controller('CartoCtrl', function($scope) {
    $scope.array = [];
    $scope.array_ = angular.copy($scope.array);
    $scope.list = [{
        "id": 1,
        "value": "apple",
    }, {
        "id": 3,
        "value": "orange",
    }, {
        "id": 5,
        "value": "pear"
    }];

});

app.directive("checkboxGroup", function() {
    return {
        restrict: "A",
        link: function(scope, elem) {
            // Determine initial checked boxes
            if (scope.array.indexOf(scope.item.id) !== -1) {
                elem[0].checked = true;
            }

            // Update array on click
            elem.bind('click', function() {
                var index = scope.array.indexOf(scope.item.id);
                // Add if checked
                if (elem[0].checked) {
                    if (index === -1) scope.array.push(scope.item.id);
                }
                // Remove if unchecked
                else {
                    if (index !== -1) scope.array.splice(index, 1);
                }
                // Sort and update DOM display
                scope.$apply(scope.array.sort(function(a, b) {
                    return a - b;
                }));
            });
        }
    };
});

Despite setting up the checkbox as per the directive in the provided link, I encountered an issue where the checkboxes were not clickable. Could this mean that the directive is malfunctioning? I am unsure of what went wrong as I merely copied the code from the reference link. Can someone assist me in resolving this issue?

Thank you for your help!

PS: I suspect that the problem may be related to materialize, but I am unsure how to address it.

Answer №1

It appears that there may be an error in the module name you have used. Upon recreating your provided code snippet, I was able to confirm that it is functioning correctly: JSFiddle

Here is the code:

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
  $scope.array = [];
  $scope.array_ = angular.copy($scope.array);
  $scope.list = [{
    "id": 1,
    "value": "apple",
  }, {
    "id": 3,
    "value": "orange",
  }, {
    "id": 5,
    "value": "pear"
  }];
}

myApp.directive("checkboxGroup", function() {
  return {
    restrict: "A",
    link: function(scope, elem) {
      // Determine initial checked boxes
      if (scope.array.indexOf(scope.item.id) !== -1) {
        elem[0].checked = true;
      }

      // Update array on click
      elem.bind('click', function() {
        var index = scope.array.indexOf(scope.item.id);
        // Add if checked
        if (elem[0].checked) {
          if (index === -1) scope.array.push(scope.item.id);
        }
        // Remove if unchecked
        else {
          if (index !== -1) scope.array.splice(index, 1);
        }
        // Sort and update DOM display
        scope.$apply(scope.array.sort(function(a, b) {
          return a - b
        }));
      });
    }
  }
});

HTML:

<div ng-controller="MyCtrl">
  <div ng-repeat="item in list">
    <input type="checkbox" checkbox-group />
    <label>{{item.value}}</label>
  </div>
</div>

Answer №2

A minor setback occurred as a result of having both bootstrap and Materialize frameworks installed simultaneously. A conflict arose between the two, but upon removing bootstrap, everything functioned smoothly once again.

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

"Instead of opening the page in a popup window, use window.open to open it in a new tab

I am attempting to open a new popup window using this JavaScript code: window.open(myUrl, ""); However, some users are experiencing the page opening in a new tab instead of a popup window. Does anyone know why this may be happening? ...

Exploring the DOM in JavaScript: Searching for the final ancestor containing a specific attribute

Check out this example of HTML code: <div id="main1" data-attribute="main"> <div id="section2" data-attribute="subsection"> <div id="nested3" data-attribute="sub-subsection"> </div> </div> </div> <div id= ...

Is there a way for me to retrieve the data returned from a worker thread?

In my quest to understand how worker-threads function, I've come across this useful example: https://github.com/heroku-examples/node-workers-example.git REMINDER: Ensure Redis is installed and running for this example My primary challenge lies in r ...

Discover the process for animating the change of grid item size using Material UI

I am currently working on a project that involves React and Material UI. One challenge I am facing is figuring out how to animate a grid item size change. The default size of the item is set to sm={3}, but when a user hovers over it, I want it to expand t ...

The JavaScript function throws an error stating "unlawful return statement"

I am currently working on a task that involves identifying which radio inputs are selected in order to pass that information to my main.js file in Electron. function checkType(){ const types = document.getElementById('type').children; ...

JavaScript: Retrieving Values Following the Execution of Numerous Conditional Statements

I'm facing a situation where I have an Object that needs to be iterated through in order to run a series of IF statements against it. Each IF statement triggers an HTTP Request, with the results being stored in an Array. My main challenge is ensuring ...

Constructing links for API and view in Flask

In the process of developing a flask application with angularjs frontend, I have encountered an issue where templates are not being rendered from Flask yet, as they are currently delivered as static files. The API endpoint in question is shown below: @rou ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

How is it possible that the whitelist in NestJs does not generate errors when using an incorrect

I am implementing a white list in my route's body validation to ensure that only data conforming to my model is accepted. If any parameter is sent that is not part of my model DTO, an error should be thrown. Here is my DTO: export class RegisterDTO ...

What is the best way to add elements to an array?

https://i.sstatic.net/NmQN6.png On the user interface, checkboxes are provided for specific operations. <input type="checkbox" className="form-check-input" name="Dashboard" value="Read" onChange={this.get_permission.bind(this)}/> <input type ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...

Using JavaScript to add a JSON string from a POST request to an already existing JSON file

I am currently working on a basic express application that receives a post request containing JSON data. My goal is to take this data and add it to an existing JSON file, if one already exists. The key value pairs in the incoming JSON may differ from those ...

Issue with Vue.js where the v-if directive placed inside a v-for loop does not properly update when

I want to dynamically show elements from an array based on boolean values. However, I am facing an issue where the element does not disappear even after the boolean value changes. <li v-for="(value, index) in list"> <span> {{ value[0] }} & ...

AngularJS: Utilizing services to make API requests and retrieve JSON data

I am struggling to pass a value from an input field on the view using a service. The service is supposed to call my WebAPI2 and then receive a valid JSON as a response. Unfortunately, I keep getting a promise object that I cannot resolve (even with ".then ...

Retrieve the element's name with jQuery

In my form, there is a select element with the name field_p_payment[value] and I am trying to reset this select box. I attempted to do this by using the code below: document.getElementsByName("field_p_payment[value]").selectedIndex='0' Unfortun ...

Attempting to verify the existence of a value in an SQL table prior to insertion

I have a simple table that contains an ID column and a location name column. Additionally, I have created an HTML form where users can input a new location into the table. Before adding the new location, I want to check if that location already exists in m ...

Incorporate distinct items into an array using reactjs

I'm facing an issue where clicking on a certain element multiple times adds it to my array multiple times. I need help in figuring out how to add only unique elements to the array. Can anyone offer some guidance? Thank you in advance. const handleCli ...

Obtain the closest numerical range using JavaScript

I have a range object and an array of price values. My goal is to find the nearest range from the range object for each value in the price values array. I attempted the solution below, but it did not give me the correct range. range = { 0: '25-500 ...

Display real-time elapsed time since a specified date using Vue JS

Is there a way to display a dynamic time elapsed without having to refresh the page every time? In my current code, I pass a created_date (defined from controller) to the script. The script then calculates the hours, minutes, and seconds before returning ...