Implementing event listeners with Angular UI-Router

Currently, I am working with Angular 1.4.5 and Angular Ui Router. I am facing an issue where I am trying to utilize addEventListener to execute a function when a text field is blurred. The challenge I am encountering is that during the load state, the element I am targeting does not exist yet because it is not present in the loaded template. As a result, the event listener never gets attached to the element.

Is there a way, preferably using Vanilla JavaScript, to add event listeners when transitioning between routes or trigger the function when navigating to different states, without having to manually edit each template to include initEventListeners() or adding onblur to every necessary element?

Below are the relevant portions of the JavaScript code, with the remaining parts properly connected using UI-Router and Angular:


function initEventListeners() {
    'use strict';
    if (document.contains(document.getElementById('phone'))) {
       document.getElementById('phone').addEventListener('blur', formatPhoneNumber);
    }
}

window.onload = function () {
    'use strict';
     runTicker();
     setTimeout(cycleFooterText, 4000);
     initEventListeners();
}

Answer №1

Utilize an Angular directive for DOM manipulation or adding listeners. Your directive will only initialize when your state is loaded, eliminating concerns about DOM selection/loading, and it's considered a best practice.

Here's an example of a directive that adds text to your input value on blur:

HTML part:

<input type="text" add-test>

JS part:

angular
    .module('testApp', []) // initialize angular
    .directive('addTest', function() {

        // directive options
        var directive = {
            restrict: 'A',
            compile: compile
        };

        return directive;

        // using compile instead of link to avoid changing the listener on scope change
        function compile(elem, attr) {

            var input = elem[0];

            input.addEventListener('blur', formatPhone);

            function formatPhone(e) {
                input.value += 'test';
            }

        }

});

Check out this fiddle: https://jsfiddle.net/kc6pofdz/1/

Also, here's a guide for those who want to delve deeper into directives: https://www.sitepoint.com/practical-guide-angularjs-directives/

Answer №2

In this scenario, it's best not to use a vanilla approach because angular directives are specifically designed for this purpose. By creating a custom directive and binding it to your #phone elements, the blur functionality will automatically be applied to your elements.

However, if you prefer not to make any changes to your templates, you could consider invoking your initEventListeners method within a $viewContentLoaded callback. You can find more information about this in the documentation here.

When dealing with a controller for a template containing <input id="phone"> elements

$scope.$on('$viewContentLoaded', 
function(event){ initEventListeners(); });

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

The Modal Textarea refreshes each time it is clicked

Whenever I try to type on the modal with 2 textareas, it stops and exits the textarea. The issue seems to be with onChange={event => setTitle(event.target.value)}, but I'm not sure how to fix it. <Modal.Body> <form onSub ...

Switch up the position of an element every time the page is refreshed

I have a webpage containing 5 images, each measuring 48px by 48px. I would like these images to be displayed in random positions on the page every time it is loaded. While I am aware that I will need to use CSS and JavaScript for this task (specifically f ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...

Despite my usage of className, I still encounter the error message "Error: Invalid DOM property `class`."

I am having trouble debugging this issue as I am unsure of the exact location of the error. Here is the link to the repository: https://github.com/kstaver/React-Portfolio Error #2. There are three more promise rejection errors present, which I will addres ...

Uploading directly to AWS S3: SignatureDoesNotMatch error specifically for Internet Explorer users

My process involves using Amazon Web Service S3 for uploading and storing files. I create a pre-signed URL using the AWS SDK for Node.js on the server-side to enable direct file uploads from the browser through this signature URL. The Process On the serv ...

Having issues with $emitting not working for parent-child components in Vue. Any ideas on what I might be doing incorrectly?

I have a login component that I need to call in the main vue component of App.vue. Within the login vue, when I click on any button, it should activate another vue component using Vue.js router to replace the login page. I have searched for solutions but h ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...

Unexpected token error occurs when using map-spread operator in vue-test-utils combined with jest

I recently set up testing for my Vue project by following the instructions provided in this helpful guide here Upon completion of the guide, I proceeded to create a test for one of my components. However, when I ran jest, I encountered the following error ...

Page Not Found: Troubleshooting Express Server Issue

Currently, I am working on creating a basic parser using Node/Express and Cheerio. However, even though the server is running smoothly, I am unable to load any pages in my browser. Below is the code snippet from server.js: var express = require('expr ...

What is the best way to extract the image url from a page in WordPress?

Is there a way to extract the image URL in WordPress dynamically for use as a reference in a script? When I use postimage(); it extracts this: <a href="address"> <img width="300" height="300" src="image.png" class="image" alt="" title="LINKING"/& ...

The animation unexpectedly resets to 0 just before it begins

Currently, I am developing a coverflow image slider with jQuery animate. However, there are two issues that I am facing. Firstly, when the animation runs for the first time, it starts at `0` instead of `-500`. Secondly, after reaching the end and looping b ...

Error encountered: `unexpected token within ES6 map() function`

Do you see any issues with this code snippet? render(){ return ( var users= this.state.users.map(user => <li key={user.id}>{user.name}</li> ) <ul>{users}</ul> ) } I am receiving an error mes ...

Exploring Angularjs End-to-End Testing using Angular-UI's Select2 Component

I am facing a challenge with a partial that has a select2 element using Angular UI http://angular-ui.github.io/ The problem is that the element is marked as required, and even though I have managed to set the field through the code provided below, the req ...

Float: A threshold reached when adding 1 no longer has any effect

In the realm of programming, float serves as an estimation of a numeric value. For example, 12345678901234567890 === 12345678901234567891 evaluates to true However, 1234567890 === 1234567891 yields false Where does the equation num === num+1 reach a br ...

Setting up a Web application testing environment on its own

Embarking on my journey in web application development and testing, I am currently involved in a project that requires me to create a standalone environment for testing the web application. The main goal is to ensure the web application is easily testable ...

Transform jQuery code into vanilla JavaScript

I'm struggling with converting this part of code from jQuery to plain JavaScript. I've documented everything in a JSFiddle as an illustration. The following is the script: $(".button").click(function () { $pageID = $(this).attr('name& ...

Why is my model binding acting strangely?

My AngularJs application interacts with a RESTful web service using the $resource module. The data retrieved from the resource (salesOrderResource) is stored in the model's vm.rowData. When I log this data to the console within the resource's que ...

Having trouble with ng-click in my AngularJS Restful application

I was attempting to create CRUD operations in AngularJS. Unfortunately, I am facing an issue where my ng-click is not functioning properly. Below is the code for my list.html: <div class="container"> <input type="text" ng-controlle ...

Exploring the capabilities of Jasmine testing with AngularJS's $locationChangeSuccess event

I'm trying to figure out the best way to test this code snippet. How would you suggest writing a test for it? $scope.$on('$locationChangeSuccess', function () { $(".modal-backdrop").removeClass('modal-backdrop' ...