Error in AngularJS: el.bind is not a valid function

While working with a custom directive in AngularJS, I encountered an issue. I wanted to scroll the window to the data-target element upon clicking it, but unfortunately, I kept getting an error saying el.bind is not a function.

The code for the custom directive looks like this:

'use strict';

app.directive("productfinderpage", ["$window","$document", function($window, $document) {
    console.log("enter into directive");
    return {
        restrict: "AC",
        link: function () {


            // get all anchors

            var anchors = angular.element(document.querySelectorAll("a[data-target]"));


            angular.forEach(anchors, function (el) {
                el.bind("click", function (e) {
                    var targetLink = e.target.dataset.target;
                    var targetContext = angular.element(document.querySelector("[data-name=\"" + targetLink + "\""));
                    var targetContextInt = targetContext.offsetTop;
                    // initiate scroll
                    scrollTo(scrollable, targetContextInt, 225);
                });
            });


            // scroll to function
            function scrollTo(element, to, duration) {
                if (duration <= 0) return;
                var difference = to - element.scrollTop;
                var perTick = difference / duration * 10;

                setTimeout(function () {
                    element.scrollTop = element.scrollTop + perTick;
                    if (element.scrollTop == to) return;
                    scrollTo(element, to, duration - 10);
                }, 10);
            }

        }
    };
}]);

The corresponding HTML code is as follows:

<div productFinderPage class="modal-body">
    <div class="info" data-sticky="data-sticky">
        <div class="info-inner">
            <div class="lender-image">LOGO</div>
            <div class="package-name"></div>
            <div class="cta">
                <button class="primary">Add to Favorites</button>
            </div>
            <nav>
                <ul class="info-section">
                    <li><a href="#" data-target="basicInfo">Basic Information</a></li>
                    <li><a href="#" data-target="extInfo">Extended Information</a></li>
                    <li><a href="#" data-target="loanSize">Loan Size / LVR</a></li>
                    <li><a href="#" data-target="loanFees">Loan Fees</a></li>
                    <li><a href="#" data-target="services">Services</a></li>
                </ul>
            </nav>
        </div>
    </div>
    <div class="main-details">
        <div class="panel" data-name="basicInfo">
            <div class="panel-header">Basic Information</div>
        </div>
        <div class="panel" data-name="extInfo">
            <div class="panel-header">Extended Information</div>
        </div>
        <div class="panel" data-name="loanSize">
            <div class="panel-header">Loan Size</div>
        </div>
        <div class="panel" data-name="loanFees">
            <div class="panel-header">Loan Fees</div>
        </div>
        <div class="panel" data-name="services">
            <div class="panel-header">Services</div>
        </div>
    </div>
</div>

You can check out the functioning of this code on jsfiddle.

Answer №1

When iterating through an Angular element, you will receive the raw document elements that must be converted back into an Angular element:

var links = angular.element(document.querySelectorAll("a[data-target]"));

angular.forEach(links, function(element) {
     var el = angular.element(element);
     el.bind("click", function(event) {
         // do something on click
     });
}

Check out this jsfiddle example

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

Uploading files to a local drive using AngularJS

As a newcomer to angularjs, I have been researching extensively on file uploading but have not come across any relevant topics for the specific case I am about to describe. In the code below, I would like to implement a feature where users can select a fi ...

Issue with Vanilla JS form validation in Bootstrap 4

I successfully created a script to validate my Bootstrap 4 form, but I'm facing an issue where the error message is replacing the input field. Should I pursue validating BS4 with Vanilla JS or stick to using Bootstrap validation? What's the indus ...

Discover the steps for dynamically integrating ionRangeSliders into your project

Recently, I integrated ionRangeSlider to display values to users using sliders. To set up a slider, we need to define an input tag like this: <input type="text" id="range_26" /> Then, we have to use jQuery to reference the input tag's ID in or ...

Combining two JSON datasets and presenting the merged information

I need help parsing two sets of json data from the following URLs: https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json My goal is to di ...

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...

Incorporating jQuery to Load Content into a DIV while preserving the original JavaScript

I am attempting to implement the following <script> $(document).ready( function() { var data = 'testing' $("#about").on("click", function() { $("#main-content").load("/about.html"); ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

Easily create svg charts for use on both servers and mobile devices

Looking to create a consistent bar chart on both desktop and mobile devices using SVG. Considering using d3.js with node.js for this purpose. Willing to run node.js on the server side. How can I write JavaScript code that works on both server and client si ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

Using AngularJS to send an HTTP request to a Node.js API

After successfully setting up an API with NodeJs (I can view the JSON result in my Browser), I encountered a problem while running a socket.io chat in Angular on port 3030 via http. Additionally, I am running an apache server with xampp to serve the fronte ...

Creating a variable to store the data retrieved from a package

Imagine you have a functioning code snippet like this: const myPackage = require('myPackage'); myPackage.internal_func(parameter).then(console.log); This outputs a JSON object, for example: { x: 'valX', y: 'valY' } ...

unveiling the secrets of a data URL using php

I am seeking help with decoding a data URL in PHP. The data URL is obtained through an AJAX request. I have used a file reader to obtain the encoded data URL of an image. This data URL is then sent to PHP via AJAX: $.ajax({ url: app, async: false, ...

Protractor End-to-End Testing Issue: Module 'selenium-webdriver' Not Found

Error: Module 'selenium-webdriver' Not Found After globally installing protractor and selenium-webdriver with the command npm install -g protractor webdriver-manager update, I encountered an issue while requiring the 'selenium-webdriver&apo ...

What is the process for creating custom event bindings in AngularJS?

There is a custom event called core-transitionend (specifically triggered by Polymer), and I am able to specify an event handler using document.addEventListener(). However, what would be the most recommended approach for achieving this in AngularJS? Alter ...

Verify the validity of the user's input

Using knockout.js and knockout.validation, I have created a book view model with properties for the author's name and book title: function BookViewModel(bookObj) { var self = this; self.AuthorName = ko.observable(bookObj.AuthorName) ...

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...