Activate validation when the scope of a custom validator is modified

Consider a scenario where we have a custom validator with an input as the attribute's value.

app.directive('inputRequired', function() {
    return {
        require: 'ngModel',
        scope: {
            inputRequired: '='
        },
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$validators.inputRequired = function(modelValue) {
                return !(scope.inputRequired && ctrl.$isEmpty(modelValue));
            };
        }
    };
});

In our scope, we define a variable and a function to toggle the variable's value:

$scope.isRequired = false;

$scope.toggle = function() {
    $scope.isRequired = !$scope.isRequired;
};

Next, we create a form where this custom validator will be used. We also include a button that triggers the toggle function.

<form>
    <input type="text" ng-model="someModel" input-required="isRequired"/>
    <button ng-click="toggle()">toggle</button>
</form>

How does it work? Initially, when the form loads and the scope is initialized, the value of isRequired is set to false, making the input field not required. When we click the toggle button, the value of isRequired changes to true. However, validation is not triggered even though a variable on the validator's scope was updated.

It's worth mentioning that this example serves only as a demonstration. While the ng-required directive can achieve similar functionality, we need a more general solution for cases where a validator depends on an input, and the field must be revalidated immediately if that input changes.

Answer №1

After some investigation, I came up with a solution: By adding a watcher on the scope within the link function and triggering $validate when there is a change in inputRequired.

app.directive('inputRequired', function() {
    return {
        require: 'ngModel',
        scope: {
            inputRequired: '='
        },
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$validators.inputRequired = function(modelValue) {
                return !(scope.inputRequired && ctrl.$isEmpty(modelValue));
            };

            scope.$watch("inputRequired", function() {
                ctrl.$validate(); 
            });
        }
    };
});

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

Animating range tick movements as the range thumb moves

My custom range input includes a span that displays the range's value and a div with multiple p elements acting as ticks. To create these ticks, I had to use a custom div because using "appearance: none" on the range hides the ticks by default. The ti ...

Exploring Angular Factory: Creating the getAll method for accessing RESTful APIs

In my Angular.JS factory, I am retrieving data from a REST Api. The REST Api endpoint is "/api/getSsls/1", where 1 represents the page number. The API response is in JSON format and contains the first ten items along with total pages/items information. I ...

Is it possible to use both MUI makeStyles and Theming in the _app.js file?

I've been working on a complex navigation component using MUI Persistent Drawers within a React + Next.js setup. To achieve the desired content shrinking effect based on state changes, I ended up placing the entire navigation system inside the _app.js ...

I'm running into an InvalidSelectorError and I could use some assistance in properly defining

As I gaze upon a massive dom tree, my task using NodeJS/Selenium is to locate an element by the title attribute within an anchor tag and then click on the associated href. Despite being a newcomer to regex, I am encountering numerous errors already. Below ...

What is the best way to incorporate multiple versions of jQuery on one webpage?

Is it possible to use multiple versions of jQuery on a single page? I need two different versions for various functions, but they seem to be conflicting with each other. If I implement jQuery noconflict, will the product scripts still work? <script typ ...

Vue Js does not include images in the dist directory when the build process is completed

In my VueJs 3 project, I am working with a list of PNG images stored in the src/assets/pngs/ directory. Within my Vue component, I use a For loop to dynamically create the list by setting the image name as the source for the img tag. This implementation wo ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

Error message "Undefined error encountered when attempting to display an array of objects using jQuery and PHP through AJAX on the console"

While trying to parse a JSON using jQuery and AJAX, I encountered an issue where some objects in the Array, like the SUM(amountbet) object, are showing up as "undefined" in the console. The image above depicts the SUM(amountbet) object appearing ...

AngularJS mdDialog not supporting Tinymce functionality

I'm attempting to integrate the TinyMCE editor into an AngularJS mdDialog. Working Plunker: http://embed.plnkr.co/s3NsemdcDAtG7AoQRvLh/ Plunker with issues: http://embed.plnkr.co/fL8kGLl3b4TNdxW1AtKG/ All features are working fine except for the d ...

Discover the secrets of flying to customized coordinates stored in variables using Leaflet.js

I'm currently working on a fire location tracking website and I'm facing an issue with leaflet.js. As a newcomer to Leaflet, any assistance would be greatly appreciated! I have a script that successfully retrieves the id of a specific row from a ...

Building an anchor tag that employs the HTTP DELETE method within an Express.js app

Recently, I delved into using express.js with handlebars.js as my template engine. One task I wanted to tackle was creating a delete link that followed RESTful principles and used the HTTP DELETE verb instead of GET. After some trial and error, I discover ...

Why do static files in Node.js + Express.js on Windows take up to two minutes to load?

I'm encountering an issue in my Windows environment with Node.Js/Express.js where static JS files can sometimes be labeled as 'pending' in the browser (even with caching disabled) for up to two minutes before finally downloading successfully ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...

Creating an HTML element within a three.js globe

I have a globe created using three.js Reference: I am trying to display an HTML div at a specific latitude/longitude on the globe. Can someone guide me on how to position the div at a particular lat/long? What I've attempted: I'm currently stu ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

Content sliding to the left due to modal prompt

I've searched through various questions and answers but haven't been able to resolve this issue. There's a modal on my page that is causing the content to shift slightly to the left. I've created a sample fiddle, although it doesn&apo ...

Retrieving data response post upload with JQuery and an HTML5 Uploader

After uploading an image and receiving a successful post response with the id of the inserted image, how can I insert this response as a data-id attribute within a a tag? Where in the function does this process occur? Here is the function: function img_ ...

storing selected button ID's in an array with the help of AngularJS

I have 5 buttons with unique ids. Each id is a random name. My goal is to add these id names into an array called myClicks. I've attempted using "data.id" and "id" but neither has worked - the array remains empty. <!DOCTYPE html> <html ng- ...

Tips for using JavaScript to style an array items individually

I have currently placed the entire array within a single div, but I would like to be able to display each element of the array separately so that I can style "date", "title", and "text" individually. This is my JSON structure: [ { "date": "Example ...