When promises are passed in AngularJS, the $asyncValidator may throw an error stating "Undefined is not a function!"

I am currently in the process of refactoring my code, with the intention of achieving the following structure:

Services:

} }]).factory('UsernameRESTService', ['Restangular',function(Restangular){
    var restAngular = 
        Restangular.withConfig(function(Configurer) {
            Configurer.setBaseUrl('http://localhost:2000/');
        });

        return {
            getCarrier: function(carrierCode) {
                var usernamePromise=restAngular.one(carrierCode).get();
                return usernamePromise;
            }
}}]).factory('UsernameValidationHelper',['UsernameRESTService','$q',function(UsernameRESTService,$q){
    return{
        usernameExists: function(username){
            var deferred = $q.defer();
            deffered.resolve(true);
            return deferred.promise;
        }
}}])

Directive:

angular.module('myApp.commonDirectives', ['myApp.services']).directive('username', ['UsernameValidationHelper','$q',function(UsernameValidationHelper,$q){
    
    return {
        restrict: 'A',
        require: "ngModel",
        
        link: function(scope, element, attrs, ctrl) {
            ctrl.$asyncValidators.username = function(value){
                var deferred = $q.defer();
                    bob= UsernameValidationHelper.usernameExists("bob");
                    defer.resolve();
                    return deferred.promise;
                }
            }
        }
}])

Just experimenting at the moment due to my limited understanding of promises.

Upon calling

bob= UsernameValidationHelper.usernameExists("bob");
, I encounter a
Type Error: Undefined is not a function

What could be my mistake?

Answer №1

Although three injections were made, the directive only includes two different parameters:

['AuthService', 'DataValidator','$http', function(AuthService, $http){}]

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

What is the best way to implement jQuery after new elements have been added to the DOM?

I'm currently working on a Sentence Generator project. The program is designed to take a list of words and retrieve sentences from sentence.yourdictionary.com based on those words. The first sentence fetched from the website is displayed using the cod ...

The request to the route timed out after waiting 5000ms for a response from the server

I am a newcomer to using Cypress and I'm exploring an HTML page for testing purposes. My goal is to test the login authentication and log the body of an XHR. Here's the test code I wrote for this: describe('Login test', function () { ...

What steps are involved in testing a nextjs endpoint with Jest?

One of my challenges is an endpoint responsible for user sign up: import { createToken } './token'; // Unable to mock import { sendEmail } './email'; // Unable to mock export default async function signUp( req: NextApiRequest, res: ...

Identifying a redirection to an alternative webpage

I am currently utilizing the ASP.NET MVC platform in conjunction with the AngularJs framework. Within my home controller, I have implemented code to check for the presence of a valid license. If no valid license is found, the user is redirected to a page w ...

The document.write function causes the page to break

I have created a view that loads another view asynchronously and then replaces the current one using document.write (yes, I want to replace the whole page!): $.ajax({ type: "GET", url: myUrl, data: null, async: true, success: function (result) { ...

Is it possible to dispatch actions from getters in Vuex?

Fiddle : here Currently, I am in the process of developing a web application using Vue 2 with Vuex. Within my store, I aim to retrieve state data from a getter. My intention is for the getter to trigger a dispatch and fetch the data if it discovers that t ...

Is it possible to customize the MUI CSS for a specific menu item using the sx prop?

How can I apply the MenuItemStyle to the sx prop of a MenuItem using: const MenuItemStyle = { '&:hover': { backgroundColor: `${theme.color.secondaryHover}`, }, '&:selected, &:selected:hover': { backgroundColor: ...

Imitate a worldwide entity with Jest and Typescript

I have a React component that utilizes the global object Routes provided by the Rails gem js-routes. My component is being tested with Jest's snapshot testing feature. The issue arises when trying to mock the Routes global object in the test to return ...

Choosing options from two separate dropdown menus with the same CSS class name using JavaScript or jQuery: A guide

I am looking to update the values of two dropdowns using the same CSS properties, similar to the design shown in the attached image. Here is the HTML code snippet for reference: <div class="container-fluid" role="main" style="margin-top: 100px;"> ...

The back-end code on the server is unable to identify the variable in my req.body, as it is being flagged

At the moment, I am in the process of developing a web application that needs to transmit data from the client side to the server side whenever a specific button is clicked. However, when I click the button, the terminal consistently informs me that the va ...

The intricate field name of a TypeScript class

I have a TypeScript class that looks like this - export class News { title: string; snapshot: string; headerImage: string; } In my Angular service, I have a method that retrieves a list of news in the following way - private searchNews(sor ...

Navigating to a particular value in Vue: A step-by-step guide

In my Vue application, I have a basic table structure: <tbody> <tr v-for="(item, index) in items"> <td> ... </td> </tr> </tbody> The items are dynamically added using the unsh ...

What is the process for obtaining a compilation of JavaScript files that are run when an event is triggered?

How can I generate a list of all the JavaScript files that are triggered when a button is clicked or an input field is selected in a complex system? Is it possible to achieve this with Chrome DevTools, or are there alternative solutions available? If Chro ...

Boost the delay in the transition speed for hiding the Navbar while scrolling down with the help of Bootstrap

Hi there! I am currently learning HTML, CSS, and JS. I'm working on a homepage project using Bootstrap-5 and have successfully integrated a navbar. However, I've noticed that the navbar disappears too quickly when I scroll down. Is there a way to ...

How can you transfer data from a Writable Buffer to a ReadStream efficiently?

How do I convert a writable stream into a readable stream using a buffer? This is my code to store data from an ftp server in an array of chunks: let chunks = [] let writable = new Writable writable._write = (chunk, encoding, callback) => { chunks.p ...

Incorporating <span> elements into a comma-separated list using Jquery on every other item

When I receive a comma-separated list of items from a database and insert them into a table cell, I want to apply alternating styles to make it easier for users to distinguish between them. For example: foo, bar, mon, key, base, ball I'm looking to ...

Retrieving data from MongoDB and presenting it neatly in Bootstrap cards

I have successfully retrieved data from MongoDB and displayed it in Bootstrap 5 cards. However, I am facing an issue where all the cards are appearing in a single row if there are multiple entries in the database. What I want to achieve is to utilize the ...

What is the best method for transforming a nested object into an array of objects?

This object contains nested data var arr = [{ "children": [{ "children": [{ "children": [], "Id": 1, "Name": "A", "Image": "http://imgUrl" }], "Id": 2 "Name": "B", ...

What is the best way to display my to-do list items within a React component

I'm working on a straightforward todo application using fastapi and react. How can I display my todos? I attempted to use {todo.data}, but it's not functioning as expected. Here is my Todos.js component: import React, { useEffect, useState } fro ...

The $.each function seems to be stuck and not cycling through the

Dealing with a rather intricate JSON structure, I'm encountering difficulty iterating through it using the $.each() function. It seems to be related to the unusual 2-dimensional array passed in the value section of the standard array (hopefully that m ...