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

Can I transfer a variable from JavaScript to Python in a seamless way?

Here's a straightforward query: Is it possible to include a JavaScript variable (varExample) in the data.py line while preserving the functionality of the JSONP Python callback code (?callback=? part)? The objective is to seamlessly integrate varExamp ...

Insert newly added rows' values into the database dynamically

Hello there, I'm currently working on a PHP form that needs to dynamically add a table row when the "Add" button is pressed. I'm using a for loop to save the values, but I'm running into an issue where the data is not being saved into my dat ...

Unveil the power of the "Enter" key with these jQuery hacks

Is there a way to prevent the Enter key from being counted as a character when disabling the submit button until something is entered in a TextArea? This functionality is achieved using the Count.js.coffee script. $(document).ready -> $(".cmnt_btn") ...

What's the best way to create flying text effects - using CSS or JavaScript

Looking for a way to enhance the user experience of my shopping cart on Android and iPhone/iPod, I want to implement a feature similar to the iTunes Store where the price flies down to the total when a purchase is made. Since I use jQuery (not UI) on this ...

What is the best approach to ensure the navbar is responsive based on the viewport size?

I am working on creating a responsive webpage that will show different navigation based on the viewport size. Currently, I have written this JavaScript code: var shownav = document.getElementById('show-nav'); if (screen.width < "720"){ ...

Where to Locate a String Excluding <a> Tags?

I'm in the process of writing a JavaScript code that will scan an HTML document and identify all occurrences of a specific keyword that are NOT contained within a link, meaning not under an <a> tag. To illustrate this, let's examine the fol ...

What methods can I use to prevent repeated login requests to SalesForce databases when using Express.js routers?

Is there a way to avoid logging into SalesForce databases and passing queries on multiple routers in express.js? It's tedious to login every time. If you have any suggestions, please let me know. var conn = new jsforce.Connection({ oauth2 : salesfo ...

What are the steps to implement email validation, Saudi mobile number validation, and national ID validation in cshtml?

Looking to implement validations for the following fields: email, mobile number (must be 10 numbers and start with 05), and National ID (must be 10 numbers and start with 1 or 2) <input class="form-control" type="text" id="txt ...

using the image source in the onclick function

I have implemented the following code to convert an image to grayscale using Javascript. <body> <canvas id="myCanvas" width="578" height="400"></canvas> <script> function drawImage(imageObj) { var canvas = document.getElement ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...

Load Facebook video onto webpage using ajax technology

I have a database where I store the IDs of videos from Facebook, YouTube, and Vimeo. When I load any video via Ajax, Vimeo and YouTube videos load perfectly. However, Facebook videos do not load properly. The code obtained via Ajax includes a script requir ...

What is the process for incorporating an animated gif into a scene?

I'm trying to incorporate an animated gif in three.js. What's the best way to do it? var materialTextured = new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture('images/pin.gif'), transparent: true, ...

The Primeng Angular2 checkbox malfunctioning issue

My form setup in Angular2 CLI looks like this: Inside the component export class UsersAddComponent implements OnInit { ngOnInit() { this.userForm = this._formBuilder.group({ role: ['', [Validators.required]], others: this._for ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

Show information in a text field from JSON in SAPUI5

How can I populate a text box with data from JSON using SAPUI5? // Sample JSON data var data = { firstName: "John", lastName: "Doe", birthday: {day:01,month:05,year:1982}, address:[{city:"Heidelberg"}], enabled: true }; // Create a JS ...

Require.js and R.js optimizer overlooks shimming configuration

I am facing an issue where R.js is not loading my shim properly, causing jQuery to load before tinyMCE which results in tiny being initialized before it has fully loaded. How can I resolve this problem? build-js.js: var requirejs = require('requirej ...

Facing delays in receiving responses for inner loop in node.js

Having an issue with retrieving data from the inner loop, as there is a delay in getting it. In my code, I am fetching the user list along with their ancestors from the SQL table. The ancestors are needed to verify their root values in the hierarchy/tree ...

having difficulty sending the username and password from the HTML page to the controller in AngularJS

In my AngularJS controller, I am having trouble retrieving the values of the username and password fields after submitting the login form. Here is the HTML code for the form: <form class="form-signin" action="" method="post"> ...

fnRedraw and fnReloadAjax do not have the capability to refresh the datatable

I have been working on updating a table with new data from an ajax url. The table loads correctly the first time, but I am struggling to get it to refresh. $(function() { var datepicker = $( "#date-picker" ); var table = $("#reports1").dataTable( ...

Learn the process of filtering an array using another array

I have a collection of items set up in the following format. items = [ { id: 1, status : "Active" // Other fields tags : [{val: 'IGM', color: 'light-success' }, {val: 'Gated Out', colo ...