Comparing the $viewValue in AngularJS with the ng-model attribute or an object parameter

I am working on a dynamic form that uses ng-min/ng-max for validation. The ng-max and ng-min are connected to object parameters modelParam.maxvalue and modelParam.minvalue. I need to show an alert or error message if the value entered in the form field goes beyond ng-max or below ng-min. It sounds simple, but I ran into some issues when trying to implement this using $viewValue.

Here is a snippet of my form:

<form name="modelParamsForm" novalidate>    

<div class="form-group col-md-4" ng-repeat="modelParam in modelParams" ng-
class="{ 'has-error' : modelParamsFieldForm.value.$invalid }">

   <ng-form name="modelParamsFieldForm">

        <label class="col-md-5">{{ modelParam.paramname }}</label>              
        <input type="number" class="form-control input-sm col-md-5" ng-
        model="modelParam.value" name="value" ng-min="modelParam.minvalue" 
        ng-max="modelParam.maxvalue" required style="maxhight: 20px">
        <span ng-show="modelParamsFieldForm.value.$invalid"></span> 
        <span ng-if="$viewValue > modelParam.maxvalue">Error message</span>
        <span ng-if="$viewValue < modelParam.minvalue">Error message</span>

    </ng-form>
</div>
...     

The controller code looks pretty standard...

$scope.modelParams = {};
$scope.loadModelParams = function(modelName) {
        var req = {
                method : 'GET',
                url : urlPrefix + 'PB_OPTIMISER_GET_MODEL_PARAMS',
                params: {modelName : modelName}         
            };
        $scope.loading = true;
        $http(req).then(function(response) {
            $scope.loading = false;
            $scope.modelParams = response.data;
            $scope.modelParamsOld = angular.copy($scope.modelParams);
        }, function() {
            $scope.loading = false;
        });

    };                  

I encountered some errors with

<span ng-if="$viewValue > modelParam.maxvalue">Error message</span>
<span ng-if="$viewValue < modelParam.minvalue">Error message</span>

I believe my confusion lies in how to properly utilize $viewValue in this context.

Answer №1

Keep in mind that the $viewValue pertains to a specific ngModel instance, not a generic value. For instance, if you have multiple inputs, each will have its own $viewValue. Thus, it is essential to specify which ngModel you are addressing in the span element. One convenient approach to accomplish this within the view is by utilizing the name attributes of the form and input field. Furthermore, it's important to note that for an input, the $viewValue is a string, so when comparing it to the min and max values, you should assess its length property. Refer to the modified code below to incorporate these adjustments:

<ng-form name="modelParamsFieldForm">
    <label class="col-md-5">{{ modelParam.paramname }}</label>              
    <input type="number" class="form-control input-sm col-md-5" ng-
        model="modelParam.value" name="value" ng-min="modelParam.minvalue" 
        ng-max="modelParam.maxvalue" required style="maxhight: 20px">
    <span ng-show="modelParamsFieldForm.value.$invalid"></span> 
    <span ng-if="modelParamsFieldForm.value.$viewValue.length > modelParam.maxvalue">Error message</span>
    <span ng-if="modelParamsFieldForm.value.$viewValue.length < modelParam.minvalue">Error message</span>
</ng-form>

UPDATE

See jsfiddle with a functional example: here

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

ReactJS aligns buttons to the right

I have been attempting to align a button to the far right without success. Here is what I have tried: <Button variant="contained" style={{display: 'flex', justifyContent: 'right'}} color="primary" className="float-right" onClick={ ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

Is it possible to have a div set to close upon loading the page?

Is there a way to have the toggle function set up so that when the page loads, the div being toggled starts out closed? I don't want them to be visible until clicked on. Best regards, Joey <script type="text/javascript> $(document ...

The combination of AddEventListener in the parent and postMessage in the iframe is ineffective

As I delve into the Stripe documentation to develop a new feature, I have encountered an issue regarding the communication between a webpage and an iframe. The code in index.html: <!DOCTYPE html> <body> parent<br> <iframe src="./ ...

Is there a built-in method in Next.js 13 to secure routes from unauthorized access?

In my project, I have the following pages: /about, /user, and /user/[id]. Unfortunately, I am unable to access req.page, which provides the slug (i.e. /user/[id]), making it difficult for me to implement logic to redirect requests from unauthenticated user ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

Issue with PHP $_GET function not functioning properly in conjunction with JQuery Mobile

I am currently developing an application using a combination of JQuery Mobile and PHP. The issue at hand is as follows: I am encountering difficulties when attempting to transfer values between different pages in my JQuery mobile app (for example, from #p ...

Verify the presence of installed software on the client's machine through ASP.Net

Does anyone have any recommendations on how to verify if an application is installed on the client side in an ASP.Net application? Since ASP.Net operates on the server side, I think it would need to be accomplished using some sort of client-side scripting ...

Tips for generating table headers in a dynamically adjusted table with AngularJS

I am having difficulty creating a table with dynamic height and width, specifically with the table header. The <td> elements are displaying properly using this ng-repeat: <tr ng-repeat="set in currFormData.volume track by $index"> <td ng ...

Troubleshooting: WordPress post not uploading to custom PHP file - Issue causing ERROR 500

Our website is built using WordPress, and I was tasked with adding a function to our newsletter subscription that sends an email to a specific address based on the selected value in the form. Everything was working perfectly on my local host, but when I tr ...

Associate information with HTML elements

I've come across this question multiple times, but the solutions are mostly focused on HTML5. My DOCTYPE declaration is: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> I'm looking t ...

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

Can Javascript work together with HTML?

Can 'this' be utilized in this specific scenario? var td = document.getElementsByTagName("td"); for (var i = 0; i<td.length; i++){ td[i].id = 'abc' + i; }; for (var i = 0; i<td.length; i++){ td[i].onclick = c ...

How can I enable a button in a React application when the text input is not populating

For my Instagram MERN project, I have implemented a Comment box feature for users. The Post button starts off disabled and becomes enabled when text is entered. However, despite entering text, the button remains disabled, preventing submission. Below is th ...

The issue arises when trying to use destructured imports with Mongoose

I've been developing a straightforward Express app with ES6. In the process of creating a schema and model for Mongoose, I encountered an issue with the following syntax: import mongoose, { Schema } from 'mongoose'; const PostSchema = new ...

Ways to display a message in AngularJS when an array is empty after being filtered

I am currently displaying a list that is grouped in alphabetical order, but showing everything at once. When you click on a letter like A, B, C, etc., it should filter to show only items starting with that letter. However, if you click on a letter where t ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

JS similar to yield*: async generator

Attempting to write a recursive async generator function, I hit a roadblock when I realized I am unsure of the syntax for yield* in the context of an async generator. In a conventional generator function, I can utilize yield* to yield all values from anot ...

Is Jquery Steps causing interference with the datepicker functionality?

I am currently using the jquery steps plugin for creating a wizard on my website. However, I am experiencing some issues with the functionality of the datepicker and qtip inside the steps. Even after switching the .js references, the problem still persists ...