Is it necessary for me to generate a directive in order to leverage $asyncValidators?

Here is the code snippet that I put together:

<input class="inputField"
    id="registerUserName"
    name="registerUserName"
    ng-model="aus.registerUserName"
    ng-model.$asyncvalidators.unique="aus.isUsernameAvailable";
    ng-model-options="{ debounce: 2000 }"
    ng-minlength="5"
    ng-required="true"
    placeholder="Username"
    type="text"
    value="" />

isUsernameAvailable = function {
        return true;
}

It appears that my validator function is not being invoked. Most examples I have seen involve creating a directive for async validators. Is it possible to achieve this without resorting to creating a directive, as I attempted?

Answer №1

Indeed, it is necessary to create a directive for this purpose. The current code snippet appears to be mixing HTML within JavaScript.

In order to validate the element using the ng-model controller, you will need to create a separate directive and utilize the require property in the directive definition object.

You could also develop a directive that accepts an expression to include in the asyncvalidators, similar to your current approach.

A potential implementation could resemble the following (please note that this code has not been tested):

angular.module('app', [])
.directive('useAsyncValidators', function (){
  return {
    restrict: 'A',
    require: 'ngModel',

    link: function (scope, element, attributes, ngModel) {
      validators = scope.$eval( attributes.useAsyncValidators );
      for(var validator in validators) {
        if (typeof validators[validator] === "function") {
          ngModel.$asyncValidators[validator] = validators[validator];
        }
      }
    }
}

.controller('validateTestController', function ($scope, $timeout) {

  delayedValidator = function () {
    return $timeout(true, 1000);
  };

  alwaysTrue = function () {
    return true;
  };

  $scope.validators = {
    isNameAvailable: alwaysTrue,
    isEmailAvailable: delayedValidator
  }
});

You can then use the following markup:

<form ng-controller="validateTestController">
  <input class="inputField"
         ng-model="whatever"
         use-async-validators="validators" />
</form>

This setup would validate the field with the validator named isNameAvailable using the function

alwaysTrue</code, and another validator on the same field called <code>isEmailAvailable
utilizing delayedValidator.

While the provided validator functions may not have practical implications, the concept showcased here involves only a few lines of code to implement a generic directive achieving your desired outcome.

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

Guide to deactivating an input field in an angular js smart search dropdown

I'm struggling to figure out how to disable or make an input field read-only for AngularJS. The issue is that users are entering values not available in the dropdown list. Previously, I attempted using the disable property, but this ended up disablin ...

Counting radio buttons in AngularJS and handling undefined values when passing parameters

After spending countless hours trying to figure out how to count radio buttons, I encountered another issue where the value passed to ng-change would become "undefined". My question is, how can I successfully pass that value? Any assistance with counting o ...

What is the process for implementing filtered HTML attributes in a directive?

I’ve created a custom directive that generates a popup menu by extracting data from HTML content. The purpose is to transform a group of Bootstrap carousel-compatible elements into a structured list. However, each .item element contains an attribute with ...

Angular: Exploring the differences between $rootScope variable and event handling

I have a dilemma with an app that handles user logins. As is common in many apps, I need to alter the header once the user logs in. The main file (index.html) utilizes ng-include to incorporate the header.html I've come across two potential solution ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

Angular 2 - Changes in component properties not reflected in view

I'm currently delving into Angular 2 and as far as I know, interpolated items in the view are supposed to automatically update when their corresponding variable changes in the model. However, in the following code snippet, I'm not observing this ...

"Utilize a special filter to set a specific item as selected in ng

Is there a way to set the selected value of ng-repeat using a unique filter? <div ng-controller="myAppList"> <select ng-model="query" ng-options="c.cat as c.cat for c in products | unique:'cat'"> <option value="0">D ...

The access-control-allow-headers token is absent from the CORS header 'Access-Control-Allow-Headers' during the CORS preflight process

I am facing an issue with two VS projects: one has MVC5 controllers exposed, while the other is an Angular client. I need the Angular client to be able to query the controllers. I have done some research and attempted the following steps: I added the f ...

Guide on implementing factory updates to the display

I am attempting to update a reference within my factory in an asynchronous fashion, but I am not seeing the changes reflected in my view. View <div ng-repeat="Message in Current.Messages">{{Message.text}}</div> Controller angular.module(&ap ...

Show labels for data on a circular graph using angular-chart.js

I recently created a pie chart using angular-chart.js and it's functioning smoothly. However, I'm facing an issue with displaying the data value on each section of the pie chart. My attempt to use Chart.PieceLabel.js by adding the code snippet b ...

Access social media login functionality from the client side using AngularJS

I am currently implementing social login in Angular using satellizer. However, I came across a section in the documentation that mentions the need for server-side code as well. The specific lines are provided below: "Additionally, authorization (obtaining ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

Combining Arrays in AngularJS with an owl-carousel Setting

My goal is to implement an endless scrolling carousel in AngularJS using owl-carousel. The idea is to load new items every time the carousel is fully scrolled and seamlessly merge queried elements with the existing list. However, I've encountered a pr ...

Executing a function upon the loading of a template in AngularJS

I have been searching through various responses here, but I haven't come across one that addresses my specific problem. Apologies if this has already been answered. I am a beginner in angular js and have recently begun working on angular routing. I am ...

Enhancing your Angular JS web application with ngCordova

As a beginner in Angular development, I am exploring the process of creating a responsive form within an AngularJS web application to enable users to upload files or photos from a mobile browser. Before proceeding with the uploads, I need to access and che ...

Using TypeScript to retrieve a strongly typed promiseValue from an angular $modalInstanceA

New to TypeScript Question: I'm working on returning a strongly typed promise from angular's $modalInstance. Here is an example of what I have: this.$modal.open(options).result.then(result => { At the moment, 'result' is of typ ...

angular-chart custom tooltip positioning issue

Hello everyone! I'm having trouble fixing the tooltip position when hovering over a point. I've searched through various posts on StackOverflow and have tried all the examples provided in my implementation: https://github.com/chartjs/Chart.js/tr ...

An excellent server-side resolution for the Angular.js

Currently, I am utilizing Angular.js for my project. The core logic of the business is developed within Angular and there are two specific areas I really need assistance with: I am in search of a seamless method to authenticate users, but I'm unce ...

AngularJS is throwing an error because it is unable to access the property `$valid` on an undefined object

I am currently working on a web application using AngularJS and I have created the following form: <form name="form2" novalidate><multiselect class="input-xlarge" multiple="true" ng-model="selectedCar" options="c.name for c in cars" change="selec ...

Setting up and customizing Express with Angular

Currently working on a straightforward Angular/Express todo-list app, I encountered some difficulties. As the project is still in progress, after running the code on localhost:3000, I noticed that {{ thing }} was displayed literally on the webpage. The di ...