AngularJS Error: $element.find(...) does not support iteration

I'm attempting to utilize a datatable in my AngularJS application. Below is the HTML code I've implemented:

   <div ng-app="datatable">
                             <div ng-controller="voucherlistcontroller">
                                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"
                                       my-table="overrideOptions"
                                       aa-data="voucherList"
                                       ao-column-defs="columnDefs"
                                       fn-row-callback="myCallback" >
                                    <thead>
                                    <tr>
                                        <th>VIN Date</th>
                                        <th>VIN No</th>
                                        <th>Receive Type</th>
                                        <th>Amount</th>
                                        <th>Particulars</th>
                                        <th>Posted</th>
                                        <th>Status</th>
                                        <th>Preview</th>
                                    </tr>
                                    </thead>
                                    <tbody ng-repeat = " vlist in voucherList">
                                            <tr>
                                                <td>{{vlist.vindate}}</td>
                                                <td>{{vlist.vinno}}</td>
                                                <td>{{vlist.receivetype}}</td>
                                                <td>{{vlist.amount}}</td>
                                                <td>{{vlist.particulars}}</td>
                                                <td>{{vlist.posted}}</td>
                                                <td>{{vlist.status}}</td>
                                                <td>{{vlist.preview}}</td>
                                            </tr>
                                    </tbody>
                                </table>
                             </div>
                         </div>

Below is the angularJS code I've utilized:

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

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "sDom":"lftipr",
                    "searching": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": true,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true
                };
            }

            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
                explicitColumns.push($(elem).text());
            });
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);
            }

            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
            }

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
            }

            var dataTable = element.dataTable(options);

            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {
                    dataTable.fnClearTable();
                    dataTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });
        };
    });

dialogApp.controller("voucherlistcontroller" ,function Ctrl($scope) {

    $scope.message = '';

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
                    $scope.someClickHandler(aData);
                });
            });
            return nRow;
        };

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;
        };

        $scope.columnDefs = [
            { "mDataProp": "vindate", "aTargets":[0]},
            { "mDataProp": "vinno", "aTargets":[1] },
            { "mDataProp": "receivetype", "aTargets":[2]},
            { "mDataProp": "amount", "aTargets":[3]},
            { "mDataProp": "particulars", "aTargets":[4]},
            { "mDataProp": "posted", "aTargets":[5]},
            { "mDataProp": "status", "aTargets":[6]},
            { "mDataProp": "preview", "aTargets":[7]}
        ];

        $scope.overrideOptions = {
                                "bStateSave": true,
                                 "sDom":"lftipr",
                                "searching": true,
                                "iCookieDuration": 2419200, /* 1 month */
                                "bJQueryUI": true,
                                "bPaginate": true,
                                "bLengthChange": false,
                                "bFilter": false,
                                "bInfo": false,
                                "bDestroy": true
        };


        $scope.voucherList = [--some data-];

An error message shows up stating - TypeError: element.find(...).each is not a function at Object.. While all the necessary references have been provided on the HTML page, such as:

Any suggestions on how to resolve this issue will be greatly appreciated. Thank you!

Answer №1

The reason for the error is that the element is a DOM element, not a jQuery object. The correct code snippet should be:

 $(element).find('th').each(function(index, elem) {
            explicitColumns.push($(elem).text());
        });

Instead of:

 element.find('th').each(function(index, elem) {
            explicitColumns.push($(elem).text());
        });

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

I am looking to create a counter in NextJS that will store its value in a database for persistent storage. How can

In my NextJS and ReactJS project, I am creating a like-counter feature that will keep track of the number of likes a user can give. The maximum limit for likes is set to 100. The count is stored in a FaunaDB. While I have successfully displayed the curren ...

Inserting a new row into a DataTable that has pagination activated, and displaying the recently added row

I am using JQuery DataTables to dynamically insert a row into a paginated table. Here is how I initialize my DataTable: $('#tasksTable').dataTable({ "bProcessing": true, "sAjaxSource": "/admin/gettaskstable", "sAjaxDataProp": "Data" ...

Tips for implementing Papa Parse to parse CSV files using JavaScript

I've been exploring their API without much luck. My goal is to extract data from CSV files that are sent to the client upon server entry. Here's the code snippet I attempted: // Attempting to parse local CSV file Papa.parse("data/premier leagu ...

What is the best way to modify the text color within a Navbar, especially when the Navbar is displayed within a separate component?

First question on StackOverflow. I have a Next App and the Navbar is being imported in the _app.js file. import Navbar from "../Components/Navbar"; function MyApp({ Component, pageProps }) { return ( <> <Navbar /> ...

What is the best way to transfer a value to the database using a distinct module?

I have recently set up a basic express project and added a file named lib/userhandler.js in the main directory. //lib/userhandler.js exports.addUser = function(req, res){ // Accessing our internal database variable var db = req.db; // Retrieving ...

What is the procedure for deactivating a plugin within the replace feature of CkEditor?

Is there a way to disable image-upload on specific CKEditor textareas without affecting all of them through the config.js file? I'm wondering if it's possible to achieve this using the .replace method. For example: CKEDITOR.replace("meTextarea" ...

Discovering the most recent messages with AJAX

I'm feeling a bit lost on this topic. I'm looking to display the most recent messages stored in the database. (If the messages are not yet visible to the user) Is there a way to achieve this without constantly sending requests to the server? (I ...

Switch Background Image - The image failed to display

Here is the code snippet I am currently working with. It involves displaying a background-image when clicking on a link with the class 'home-link', and not showing an image if the link does not have this class. The issue at hand: The problem ari ...

Is Ember CLI experiencing issues due to the latest Ember Data update?

Greetings! I am a beginner with Ember and recently encountered some warnings after upgrading to the latest version of Ember Data: Update: I have two identical versions of my app, one built without ember-cli and the other with ember cli. Both applications ...

Using React to fetch data and then mapping it inside a function

I am facing an issue where I need to make a request for each item in the MAP, but I want to ensure that I wait for the response before moving on to the next object. Currently, my code is sending out all the requests simultaneously, causing the Backend to c ...

Guide to showcasing object characteristics inside an object in Angular2

My USAFacts object contains properties like StateName, as well as objects like State-Bird which hold information about the state bird. If written in JSON, a record of USAFacts would appear as follows: {"StateName": "PA", "State-Bird": [ { "Name": "Ruffed ...

Modifying a $scope variable beyond the controller in AngularJS

I am trying to update a variable called $scope.outsidescope outside of the controller in my AngularJS application. The routing is done using $routeProvider, and the $scope.outsidescope variable is located outside of the ng-view. My query is how can I modi ...

Angular js is a powerful framework that allows for the seamless transition of views, except for the home

I am currently using the ng-animate module to implement sliding effects for my app views. Each route has its own unique slide animation. Take a look at my simple code below: HTML: <div ng-view ng-animate class="slide"></div> CSS: /*Animatio ...

The functionality of window.event.target appears to be malfunctioning in the Firefox browser

I have been working on an angularjs application. We have implemented a functionality to display alerts for unsaved changes using window.event.target. Everything was functioning correctly in all browsers except for <code>Firefox. The error message w ...

Is there a way to modify the color of a specific section of a font icon?

Currently, I am in the process of implementing an upvote button using fa fa signs. However, I have encountered an issue where the background color of the up vote button is bleeding outside of the sign (possibly due to padding on the icon), and I am strivin ...

Using a single package manager for both backend and frontend development - is it possible? (Yarn/NPM)

Before, I relied on NPM for server-side tasks and Bower for frontend. NPM would install packages in the node_modules/ directory, while a .bowerrc file directed package installations to public/lib. Recently, I've made the switch to Yarn from NPM, and ...

Using jQuery to establish a canvas element and define its dimensions by adjusting its width and height attributes

My attempt at using jQuery to create a canvas element was not quite as expected. Here is the code I tried: var newCanvas = $('<canvas/>',{'width':100,'height':200,'class':'radHuh'}); $(body).append(n ...

Is there a method available for troubleshooting unsuccessful AJAX requests? Why might my request be failing?

Whenever I click on a button with the class "member-update-button," an alert pops up saying "got an error, bro." The error callback function is being triggered. Any thoughts on why this might be happening? No errors are showing up in the console. How can I ...

What is the best way to set the length of an undefined item in an object to 0 in reactjs?

I am facing a challenge keeping track of scores within each article and displaying them accurately. The issue arises when there is a missing "up" or "down" item in the object. Below is the data containing all the votes: const votes = { "1": { "up": ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...