Creating a selectAll checkbox that triggers the ng-click function on each individual checkbox

I've encountered an issue with my code where clicking a checkbox triggers the ng-click function. Here is the JavaScript snippet:

$scope.selectTitle = function(evt, selected){
        evt.stopPropagation();
        var filtered = _.findWhere($scope.selectedTitles, {id: selected.id});
        var index = _.indexOf($scope.selectedTitles, selected);
        if(selected === filtered){
            $scope.selectedTitles.splice(index, 1)
        }
        else{
            $scope.selectedTitles.push(selected);
        }
        console.log('titles', $scope.selectedTitles, 'filtered', filtered, 'index', index);
     };

The code was used within a table that had ng-repeat and ng-click functionalities. I utilized .stopPropagation() to prevent the table's ng-click from being triggered.

Now, I am trying to implement a select all checkbox feature with this code:

$scope.selectAll = function (filteredTitles) {
        if ($scope.selectedAll) {
            $scope.selectedAll = false;
        } else {
            $scope.selectedAll = true;
        }
        _.forEach(filteredTitles, function(cpPortfolioItem) {
            cpPortfolioItem.Selected = $scope.selectedAll;
            if(cpPortfolioItem.Selected){
                $scope.selectTitle();
            }
     });

However, upon running the code, an error occurs stating

TypeError: Cannot read property 'stopPropagation' of undefined
.

I cannot simply remove the stopPropagation as it serves a crucial purpose. Can anyone provide suggestions on how I can successfully select all checkboxes and execute the ng-click function for each? Your help is greatly appreciated. Thank you!

Answer №1

Just a few thoughts worth considering.

Instead of adding to scope with selectedAll, it might be more efficient to keep it as a private variable inside the controller.

var selectedAll = false;
$scope.selectAll = function(){
      selectedAll = !selectedAll; // easy toggle.
      _.forEach(filteredTitles, function(title){
                    title.isSelected = selectedAll;
       }
}

Your checkboxes can directly link to the title.isSelected state for easier handling and toggling.

Take a look at: https://docs.angularjs.org/api/ng/directive/ngChecked

<input ng-checked="title.isSelected" .../>

'title' in this context refers to your ng-repeat data object.

Consider implementing a directive within your ng-repeat loop for better organization.

Here's an example directive:

angular.module('appName')
    .directive('portfolioItem', function() {
        return{
            restrict:'E',  
            replace:true,
            templateUrl:'portfolioItem.view.html',
            scope:{
                data:'='  
            }
            
        };
    });

Don't forget to create a script ng-template for "portfolioItem.view.html"

<script ng-template="portfolioItem.view.html">
    <section class="item">
     {{data}}  
     <input ng-checked="data.isSelected" ... />
    </section>
</script>

You may also want to rethink your select item function by pushing data into a factory to streamline your controllers and reduce watchers.

 angular.module('appName')
        .factory('DataManager', DataManager);

    function DataManager($log, $timeout, ItemModel) {
        var mngr, config = getConfig();  

        $log.debug('DataManager Init');

        mngr = {
            CurrentSearchTerm: null,
            Items: [],
            Abort: abort,
            GetData: getData,  
            GetMoreResults: getMoreResults
        };

        function getData(){
            dataService.getData().then(function(response){
             mngr.Items.push(parsedDataItem);
            };
        }


        return mngr;
   }

Your controller can then iterate through DataManager.Items or use filters like Underscore or Angular for enhanced data management.

Answer №2

This solution may not be the most visually appealing, but it serves two purposes: only handling evt if it is defined, and passing the element into selectTitle from selectAll. It minimizes changes to your existing code. In general, you may even be able to do without selectTitle by using ng-model on your checkbox.

$scope.selectTitle = function(evt, selected){
    if(evt) evt.stopPropagation();
    var filtered = _.findWhere($scope.selectedTitles, {id: selected.id});
    var index = _.indexOf($scope.selectedTitles, selected);
    if(selected === filtered){
        $scope.selectedTitles.splice(index, 1)
    }
    else{
        $scope.selectedTitles.push(selected);
    }
    console.log('titles', $scope.selectedTitles, 'filtered', filtered, 'index', index);
 };

--

$scope.selectAll = function (filteredTitles) {
        if ($scope.selectedAll) {
            $scope.selectedAll = false;

        } else {
            $scope.selectedAll = true;

        }
        _.forEach(filteredTitles, function(cpPortfolioItem) {
            cpPortfolioItem.Selected = $scope.selectedAll;
            if(cpPortfolioItem.Selected){
                $scope.selectTitle(null, cpPortfolioItem);
            }
     })};

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

Transformation of firebug console information into a function()

Snippet of JavaScript code: KT_initKeyHandler(b) Firebug console output: KT_initKeyHandler(b=keydown charCode=0, keyCode=90) Corresponding JavaScript function call: KT_initKeyHandler(?) Example: Snippet of JavaScript code: KT_event(b,c) Firebug ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...

Postal Code Auto-Suggest by Google

I'm attempting to create a unique autocomplete feature for a text box that specifically provides postal codes. To accomplish this, I have followed the guidelines outlined in the documentation found at https://developers.google.com/places/webservice/au ...

Develop a custom time input mask in AngularJS controller

In my AngularJS controller, I have the following code snippet: $scope.detailConfig = [{ title: $filter('translate')('bundle.app.HORA_MINUTO_INICIAL_DESCONSIDERAR'), property: 'faixaHorariaInicial', type: ' ...

Modification of a CSS element

The CSS I am working with looks like this: .cls .imageX { float:left; } .cls .imageY { float:right; } It is currently being used on a page in this way: <div class="cls"> <a href="" class="imageX"><img src="left.png"/></a> &l ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

What are the steps to incorporate a Microsoft Project Dashboard into a web application?

Currently, I am working on a project that involves incorporating an MS Project Dashboard into my Angular-based web application with a Node backend API. Our goal is to seamlessly embed the MS Project dashboard within our application. However, I am unsure of ...

Is it feasible to utilize multiple ng-app directives in AngularJS? If so, under what circumstances would we do so and what is the process for registering them with an Angular module?

Is it possible to incorporate multiple ng-app directives in a single application? How can we register both ng-app directives and what are the benefits of using more than one ng-app within an application? ...

The jQuery AJAX function appears to be unresponsive and failing to execute

I have a form that needs to update values on click of a radio button. Unfortunately, my jQuery skills are lacking. Here's what I have tried so far: HTML: <form> <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome"> ...

Implementing conditional reduction in JavaScript arrays

I've encountered an issue with the filter and reduce methods. I am attempting to calculate the sum of "smc" values only when "A" equals 2020 from the given array below: arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}] My attempted solution so ...

Utilizing Ajax to serialize or transfer JSON objects

I have received a Json object and I am looking to extract the data using JavaScript. Specifically, I need help with looping through fields and extracting the data. def For_Sale_Listing(request,id): try: listing = Listing.objects.filter(pk=id) ...

Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I&apo ...

Is it possible to load JavaScript code once the entire page has finished loading?

My webpage includes a script loading an external JavaScript file and initiating an Ajax query. However, the browser seems to be waiting for example.com during the initial page load, indicating that this external dependency may be causing a delay. Is there ...

Maintain the expanded sub-menu when the mouse leaves the area, but a sub-option has been

Implementing a side menu with parent and child options that dynamically display content in the main div on the right when a child option is selected. The parent options are initially shown upon page load, and the child options appear when the mouse hovers ...

Get rid of empty spaces in gridstack js

My latest project involves using gridstack js In the image displayed, I have highlighted the excess white space (in blue) that needs to be removed. Take a look at this visual: Any suggestions on how to eliminate this unwanted white space? ...

Creating multiple asynchronous calls within a loop in JavaScript

I am currently working on a task in my gulpfile.js that involves uploading an app using Gulp and SharePoint. 'use strict'; const gulp = require('gulp'); const build = require('@microsoft/sp-build-web'); const spsync = require ...

Feeling grateful: Enable scroll functionality for a log widget

I am currently utilizing the Blessed library to create a dashboard within the terminal. My issue lies in making the log widget scrollable. Despite implementing the code below, I am unable to scroll using my mouse wheel or by dragging the scrollbar: var l ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...