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

Not acknowledging the change quickly enough

Within a controller's logic, there is a function called newGame: function startGame(){ $scope.gameOver = true; $timeout(function(){ //perform game actions $scope.gameOver = false; }, 3000); } Meanwhile, in a dire ...

Designing a dynamic carousel with AngularJS

Currently facing an issue with handling JSON data in AngularJS. When I select the 'img' object, it logs to the console but doesn't get applied to the scope. Can anyone provide some guidance on this? 'use strict'; angular.module(& ...

How to successfully transfer input data from a dialog to a controller using jQuery and Grails

As a newcomer to Grails and jQuery, I recently created a jQuery dialog following this example: http://jqueryui.com/dialog/#modal-form The goal is to open a dialog, input data, and have it displayed in a dynamic table on the main page. Once all entries are ...

Having trouble handling file uploads in Laravel via JQuery Ajax requests

When attempting to upload a CSV / Excel file and receiving it through an ajax request, the process is not functioning as anticipated. I employed a formdata object to upload the files in this manner: const formData = new FormData() formDa ...

React code displaying misalignment between label and input

Can you help me align my URL and https:// on the same margin? https://i.sstatic.net/hxkkC.png <div className="card"> <div className="card-body"> <div className="form-group col-12"> <label cla ...

What is the best way to adjust the height and width of a div when it comes into view through scrolling?

How can I automatically and frequently change the size of my div when it is scrolled into view? HTML <div id="contact" class="fadeInBlock"> <div class="map"> <div class="pointer"> <div class="dot"></div& ...

Update a variable globally within setInterval function

Seeking assistance on showcasing the number of seconds that have elapsed using a setInterval function in JavaScript integrated within HTML. The code snippet below has been attempted, but it is only displaying 1 second and the test function appears to not ...

There seems to be an issue with the CSV file, possibly indicating an error or the file may not be an SYLYK file when

After developing a node.js script to convert an array object into CSV format using the "objects-to-csv" library from NPM, I encountered an issue when opening the generated CSV file in WPS and Microsoft Office. The warning suggested that there was either an ...

Unable to select options from the drop-down menu

I am currently using AngularJS and I have successfully generated a dropdown, however, the default selection in the dropdown is not working. Below is an example of my code: selectedindustry1 = 2 <select class="form-control" name="industry_1" id="indu ...

How to eliminate query strings from the current page's URL using JavaScript

Looking for a way to remove the querystring from the current page URL using JavaScript when a button is clicked. Can someone please provide the necessary code for this? ...

AngularJS ng-bind-html is a powerful feature that enables bi-directional data binding within

I am facing an issue with my AngularJS app where I am fetching data from a webservice and trying to bind it to the template using ng-bind-html. However, when attempting to bind the data inside ng-bind-html, nothing seems to happen. Can anyone help me with ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...

Basic Node.js messaging application excluding the use of socket.io

Recently, I've delved into learning Node.js and embarked on creating a basic chat application. It appears that socket.io is the go-to option for most developers, but I'm keen on grasping the concept from a more foundational standpoint using GET a ...

Sharing a session with a Django template using jQuery

I am attempting to use $.load() to load a Django template that contains {% if user.is_authenticated %}. However, when the template is rendered on the server in response to an AJAX-generated HTTP request, the user object is undefined. Here is my_template.h ...

Having difficulty utilizing the $.each() function to assign properties to an object

I have an object called habits that contains some values. var habits={ "Drinking":"No", "Smoking":"No" } I want to add the values from this variable into another variable in the following format: var NewHabits = new Object(); Ne ...

Error: The provided `anchorEl` property for this component is invalid

While working on my React 18.2 app with MUI 5.10.5, I encountered an issue trying to create a <Menu /> element that should open when a button is clicked. The menu does appear, but the positioning seems off as it displays in the top-left corner of the ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

Switch from manipulating the DOM to using Angular binding to update the td element with fresh information

When I click the edit button on a tr Element, the tdElement for the redirectUrl should become editable. By using the id of the tdElement and changing the contenteditable attribute to true, I can then use JQuery to retrieve the newly typed data. <tr ng- ...

Seeking assistance in the development of a visual depiction of device orientation through JS

My goal is to visually represent the device orientation values alpha, beta, and gamma by creating a series of "bars" for each value. Currently, I have managed to display only the values in plain text using innerHTML. However, I envision these bars moving i ...

How can AngularJS display ellipses using the limitTo filter exclusively for strings that surpass the character limit?

Looking to use the limitTo filter on strings? If a string is under 10 characters, it will be displayed as is. But if it's longer than 10 characters, I need to cut it off at the tenth character and display ellipses. Is there an easy way to do this with ...