Check and validate the adjacent field whenever a change is detected in this field in Angular

Currently, I have a select menu with options and a text field that accepts numerical input. The text field needs to adhere to specific ranges based on the selection from the select menu, which is managed through custom validation. My dilemma lies in triggering this validation when the select option changes.

I initially attempted to include an ng-change directive directly in the HTML:

<select ng-change="$scope.my_form.numberField.$validate()">

However, this method proved ineffective. Subsequently, I crafted a function within the controller:

$scope.myFunction = function(){
    $scope.my_form.numberField.$validate();
}

Afterward, I modified the select element to call this function:

<select ng-change="myFunction()">

Further experimentation involved tweaking the code within the function:

console.log( $scope.my_form.numberField.$validate() );

Unfortunately, this resulted in an "undefined" output. The corresponding HTML for the text field appears as:

<input type="text" name="numberField" ng-model="numberField" number-validate>

Despite successful validation when directly updating the field, I am at a loss concerning how to automatically trigger it upon changing the select field. Any suggestions or insights would be greatly appreciated.

Answer №1

After reviewing my current approach, I have a lingering question about why calling $validation() didn't work as expected. If anyone has insights on this issue, please feel free to share.

To address the problem, I decided to update my directive by incorporating a $watchCollection method to track changes in both fields of interest.

Initially, my directive looked like this:

App.directive('numberValidate', function() {
return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
            var selectField = scope.my_form.selectField

I made adjustments to the directive code as follows:

App.directive('numberValidate', function() {
return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
        scope.$watchCollection('[my_form.numberField, my_form.selectField]', function (data) {
            var numberField = data[0];
            var selectField = data[1];

However, it is important to note that the html still requires the number-validate attribute to be included:

<input type="text" name="numberField" ng-model="my_form.numberField" number-validate>

As a newcomer to Angular, I acknowledge there might be better solutions out there, but for now, this approach is serving its purpose effectively.

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

Converting JSON to Array: A Step-by-Step Guide

Greetings, StackOverflow community! This is my inaugural question here. I believe the answer is not overly complex, but my knowledge of Javascript is quite rudimentary. Currently, I have a JQuery AJAX function that processes this JSON object: { "Users" ...

How to pass a JSON object to a component's constructor in Angular 2

In a unique situation, my primary component config.editor.component performs extensive processing and generates various JSON objects. I am content with this approach. The template for this component then proceeds to render another component - api.entry.com ...

The dynamic data graph generated by HIGHCHARTS Areaspline is not as effective as expected

I need help creating a Dynamic Areaspline graph, but the result is coming out strangely. Does anyone have any ideas on how to fix this and get a smooth series? Here is an example of the issue: http://jsfiddle.net/mchc59nb/1/ chart: { ...

Is a catch required for every then statement in AngularJS?

I need to make multiple ajax calls in order to populate a form, but I want to wait until all of them are completed before displaying the form. If there is an error during any of the calls, I want to stop processing and immediately show the first error enco ...

Can you suggest a simple method for implementing the "componentDidUpdate()" lifecycle method using just JavaScript?

I've been curious about replicating the componentDidUpdate() lifecycle method in JavaScript on my own. It got me thinking, how did React and Vue.JS create their own lifecycle methods? I attempted to study the minified version of Vue.JS but found it qu ...

Guide to implementing mongoose validation with the update() method

I have created a schema with a field that is of type number. I set the minimum value to 0, but after updating it, the value changes to a negative number. Here is my updated schema: let balanceChecker = (v)=>{ if(v<0){ return v=0; }el ...

The structure becomes disrupted when the Material Ui grid is enclosed within a div container

I currently have a responsive dashboard built with Material Ui's Grid elements. One of the grid items is wrapped in a div element, causing the layout to break. Check out the playground with the div element here: https://codesandbox.io/s/basicgrid-mat ...

Converting null to an empty string in Ionic React - A step-by-step guide

Seeking help with submitting a form through an API endpoint. The issue arises with the 'phone' input, which is not a required field and is causing validation errors. Here is the error message received when 'phone' input is left empty: { ...

Parent function variable cannot be updated within a $.ajax call

I'm facing an issue with pushing a value from inside an ajax call to an array located outside of the call but still within the parent function. It appears that I am unable to access or update any variable from inside the ajax success statement. Any as ...

Changing the position of an element in CSS using the center as the reference point, based on a JavaScript variable: How can it be done?

I have an image marking a scale, with the marker's position in HTML set as: <image class="red-marker" xlink:href="./assets/images/marker.png" [attr.x]=percentage width="12" height="40" y="0" ></image> But I want the middle of the marker ...

When I avoid using a string ref, I encounter the error message "Error: Function components are not allowed to have string refs"

Recently, I created a new component const Projects = () => { const state ={ activeItemID: 1 } const CarouselRef = useRef(null); const NextSlide = () => { CarouselRef.current.style = "opacity: 0"; } return( <Co ...

``Is it possible to adjust the style of an HTML element based on the style of another element?

Within my web application, I am dynamically changing the style of an HTML element using JavaScript. Below is the code snippet: function layout() { if(document.getElementById('sh1').getAttribute('src') == "abc.png") { docum ...

What is the process for syncing ng-model with external data sources?

Here is a question that I have pondered: Let's consider the HTML code snippet below: <div id="container" ng-controller="Controller"> <my-tag ng-model="values"></my-tag> </div> Now, take a look at the controller defined a ...

Trouble with Webpack compiling SCSS files

I'm struggling with setting up webpack to bundle my js react components, js modules, and compile my .SCSS files to css. Despite multiple attempts, I keep encountering errors. Below is an excerpt from my webpack.config.js: const webpack = require(&a ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

inquiry on php function properties

I have a PHP file containing two functions. <?php function first () { //in real case more conditions echo "first"; return true; } function second () { //in real case more conditions echo "second"; return true; } first(); second(); ?> And in an ...

Is there a scope property that relies on a different scope property?

As a beginner in Angular, I could use some guidance on binding to scopes. I'm currently working on loading data that populates a property and then updating other properties based on this initial property. Is there an efficient way to trigger this pro ...

Troubleshooting Problems with Cookie and Session Management

I'm encountering an issue while trying to set cookies and session values during login on the backend, which is built in node js. However, when react calls the API to verify these cookies or session values, they are returning as undefined... My middle ...

What is the best way to retrieve a property with a period in the method name in JavaScript?

One dilemma I'm facing is trying to access the tree.removenode method through chartContext in Angular. It's been a challenge for me to understand how to achieve this. https://i.stack.imgur.com/yG7uB.png ...

I am struggling to figure out how to make the responsive menu close

#switch image var up = 'https://image.flaticon.com/icons/svg/149/149187.svg'; var down = 'https://image.flaticon.com/icons/svg/128/128397.svg'; $('#resNavToggle').click(function() { if ($('.resNavIcon').attr( ...