Using AngularJS to retrieve DOM elements within a directive's controller

Currently, I am in the process of creating a custom image carousel directive using only AngularJS and no additional libraries.

simpleCarousel.$inject = [];

function simpleCarousel() {
    var directive = {
        restrict: 'E',
        templateUrl: 'someurl.html',
        scope: {
            // Scope variables
        },
        controller: simpleCarouselController,
        controllerAs: 'ctrl',
        bindToController: true
    };
    simpleCarouselController.$inject = [];
    function simpleCarouselController() {
        angular.extend(this, {
            next : //handle next image sliding
            prev : //handle previous image sliding
        });
        function detectSwipe(el) {
            var touchsurface = el, 
                swipeDirection, 
                startX,
                distX,
                threshold = 150,
                allowedTime = 2000,
                elapsedTime,
                startTime;

            touchsurface.addEventListener('touchstart', function(e) {
                var touchObject = e.changedTouches[0];
                swipeDirection = 'none';
                distX = 0;
                startX = touchObject.pageX;
                startTime = new Date().getTime();
                e.preventDefault();
            }, false);
            touchsurface.addEventListener('touchmove', function(e) {
                e.preventDefault();
            }, false);
            touchsurface.addEventListener('touchend', function(e) {
                var touchObject = e.changedTouches[0];
                distX = touchObject.pageX - startX;
                elapsedTime = new Date().getTime() - startTime;
                if (distX > 0) {
                    swipeDirection = 'right';
                    return swipeDirection;
                } else if (distX < 0) {
                    swipeDirection = 'left';
                    return swipeDirection;
                } else {
                    return false;
                }
            }, false);
        }
    }
}

I have managed to implement the touch event handlers. However, I am unsure about how to pass the element to the touch event. Additionally, should I handle preventing user clicks while sliding through JavaScript or use CSS with the user-select property?

Answer №1

Attaching event handlers in the controller is generally seen as a suboptimal method and not recommended.

Additionally, you may consider using ngTouch to recognize swiping gestures.

Click here to learn more about ngTouch

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

Managing Time Before Browser Refresh in AngularLearn how to monitor and examine the time remaining before

In my Angular web application, I am facing an issue where the user's login status is lost every time the browser is refreshed or reloaded. I want to implement a feature that allows the login status to remain active for a short period of time after the ...

Saving JSON format in VueX State Management

I'm relatively new to using Vue/VueX and I am exploring methods for storing JSON data in the VueX state. Initially, it seemed like a simple task: state { jsonthing: { ... } } However, I encountered an issue where getters return an Observer type ins ...

Efficiently and consistently refreshing the DOM with information while maintaining page integrity

I'm currently developing a Single Page Application (SPA) that utilizes AJAX to dynamically load content into a specific div. The layout consists of a side accordion menu, where clicking on an item loads relevant information in a neighboring div. Howev ...

The div on my webpage is not loading its content as expected when using JavaScript

I am having trouble continuously loading the content of a div from another page. Using alert worked fine, but the page data is not loading. JavaScript <script> $(document).ready(function(){ setInterval(function(){$("#loadAvailable").load("update.p ...

Relocating to reveal or conceal item

I am currently working with jQuery and trying to achieve a specific functionality. My goal is to hide and unhide an element, while also focusing on the exposed area once it becomes visible. I have a link #welcomeselect that, when clicked, should reveal t ...

Using functions as properties in React.js

I am facing an issue while trying to pass a function as a prop. Although I have done this successfully in the past, now I am getting an error (this.props.functionName is not a function). I have a child component called Navbar and a parent component named ...

Sending Image Data in Base64 Format with Ajax - Dealing with Truncated Data

My current challenge involves sending Base64 image data through ajax to the Server. I've noticed that sometimes all the pictures are successfully sent, but other times only a few make it through. Does anyone have suggestions on how to implement error ...

The use of an Authorization header is not compatible with HTTP GET requests

I recently incorporated VueSession into my project to handle user sessions. One of the components in my application is a login form that communicates with my backend (Django) to obtain a JWT token. However, I encountered an issue where although the login p ...

Error encountered when trying to show a modal using a PHP script

I'm encountering an issue with the modal system on my website. Let me share some code snippets: MODALS ARE BUILT WITH W3.CSS LIBRARY modal.js (including debug statements) let modal = null; let title = null; let content = null; $(document).ready(() = ...

Tips for implementing arraybuffer playback in video tags

I have been exploring ways to convert images from an HTML canvas into a video. After much research, I just want to be able to select a few images and turn them into a video. By passing multiple images to a library engine, I am able to receive an array buff ...

Which is the Better Choice for an MMO WebSocket Server: Node.js or C++?

Contemplating creating a live game using WebSockets for the web has been on my mind. With my knowledge of Node.js, it's tempting to develop it there. However, C++ appears to be the favored server language due to its speed. Would it be best to try bui ...

The debugger extension for Visual Studio Code in Chrome, [webkit-debug-adapter], received a response from the target application, but was unable to find any valid target

I am currently working on an Angular/TypeScript application and have been able to debug the TypeScript code in Chrome thanks to the map files. Recently, I decided to install the Debugger for Chrome extension from Visual Studio Marketplace. You can find it ...

Instructions for downloading a file using Front End technology in Java and HTML

I am looking to initiate a file download upon clicking a button on the front-end interface. Front End <td><a name="${flow.name}" data-toggle="tooltip" title="Report" class="generateReport"><span class="far fa-file-excel"></span>&l ...

Passing arguments to EJS view with Express

As a newcomer to Node.js/Express/EJS, I've made an interesting observation. I've realized that if I pass arguments from an Express request handler to an EJS view without specifying the argument name, it automatically assigns a name based on the v ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

Utilize state objects and child components by accessing sub-values within the object

I have a Dropzone component where multiple uploads can happen simultaneously and I want to display the progress of each upload. Within my Dropzone component, there is a state array called uploads: const [uploads, setUploads] = useState([]) Each element i ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...

changing the value of a global variable from inside a function

Currently, I am working with Vue in an attempt to assign values to checkboxes. Below is the code snippet: let variable = false; export default { name: "nyle-home", created() { this.notifstate = this.$route.params.data[0].state; ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Unexpected firing of jQuery blur event upon page load rather than during the expected time

Currently, I am working on a project that involves form validation using jQuery. One element I am focusing on is the email field, where users will input their emails. I want to ensure that the email input is checked once it has been filled out. My initial ...