NgMessages in AngularJS keeps messages visible

Just starting out with learning AngularJS, so please bear with me if this question seems silly.

I want to create message boxes in my application using the ngMessages directive from Angular documentation. These message boxes should appear when specific conditions are met.

However, even after following the example provided in the documentation, I'm facing an issue where the message boxes remain visible even when their conditions are not fulfilled. On the upside, the $error variable does show the accurate values.

angular.module('ngMessagesExample', ['ngMessages']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<form name="myForm">
    <label>
        Enter your name:
        <input type="text" name="myName" ng-model="name"  ng-minlength="5" ng-maxlength="20" required />
    </label>
    <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>

    <ng-messages for="myForm.myName.$error" style="color:maroon;" role="alert">
        <ng-message when="required">You did not enter a field</ng-message>
        <ng-message when="minlength">Your field is too short</ng-message>
        <ng-message when="maxlength">Your field is too long</ng-message>
    </ng-messages>
</form>

This is how it appears: https://i.sstatic.net/ZU8VA.png

Answer №1

Presenting a different approach to address your issue.

<p ng-if="myForm.myName.$error.minlength">The length of your input is inadequate.</p>   
<p ng-if="myForm.myName.$error.maxlength">Your input exceeds the maximum length.</p>   
<p ng-if="myForm.myName.$error.required">You left this field blank.</p>

Answer №2

Looks like your code is in good shape, but you may just need to import the ngMessages module separately. (Did you check the console for any errors?)

Remember, I've optimized the performance by moving the script tags to the bottom of the body tag, although it functions correctly in the header as well.

<body ng-controller="MainCtrl">
<form name="myForm">
  <label>
    Enter your name:
    <input type="text" name="myName" ng-model="name"  ng-minlength="5" ng-maxlength="20" required />
  </label>
  <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>

  <ng-messages for="myForm.myName.$error" style="color:maroon;" role="alert">
    <ng-message when="required">You did not enter a field</ng-message>
    <ng-message when="minlength">Your field is too short</ng-message>
    <ng-message when="maxlength">Your field is too long</ng-message>
  </ng-messages>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular-messages.min.js"></script>
<script src="app.js"></script>

Plunker

Answer №3

<div ng-show="myForm.myName.$touched" id="myName" ng-messages="myForm.myName.$error" style="color:navy;" role="alert">
        <ng-message="required">Please fill out this field</ng-message>
        <ng-message="minlength">Field is too short</ng-message>
        <ng-message="maxlength">Field is too long</ng-message>
    </div>

Exclude when from your code.

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

Accessing the name attribute of the TextField component, displayed as a Select Box in Material-UI, by utilizing the event object received from the onFocus prop

Utilizing the "@material-ui/core": "4.11.2" library along with "react": "16.8.6", I've encountered an issue with the TextField component where the select prop is set to true. Specifically, I am unable to access ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...

Angular will hold off until the subscribe operation has completed before passing values to another function

Here's a function I have in the code: File: subcategory.service.ts getSubCategoriesById(inp_subCatid: String): Observable<any>{ this.getSubCategoriesList().snapshotChanges().pipe( map(changes => changes.map(c => ({ key: ...

Ember.js - Handling Asynchronous Events and Callbacks

I am not utilizing Ember Data, and I have integrated an ajax call in my Model to fetch data from a remote source. Once I have successfully retrieved the data from the API, I intend to organize/filter it based on category. My approach is to handle the filte ...

Can OpenLayers library be integrated into Vue CLI 3?

I am currently trying to integrate Openlayers with vue-cli-3, but it seems like I am missing something in the process. Initially, I installed Vue CLI using the following command: npm install @vue/cli -g Next, I added additional dependencies, specifically ...

How to send out an Array and a Variable at the same time using socket.io

Currently expanding my knowledge with Node.js, Express.js, and Socket.io. I successfully created a chat application that is functional at the moment. Now I am interested in letting the Client know when a user enters or exits the chat by emitting a variab ...

Unable to close Bootstrap 5 modal

All of my modal forms are functioning properly, except for one that I migrated from Bootstrap 4 to Bootstrap 5. This particular modal refuses to close. Neither the Close button (the X at the top of the popup) nor the Cancel button will close the modal. I ...

Synchronize data across variables or set up a listener for changing variable values?

Imagine I have a scenario with 2 variables: var connection1, connection2; connection1 = connection2 = false; There are 2 distinct functions that establish connections to a remote node and update each variable to true once connected: node1.on('open& ...

A guide on designing a personalized search bar for MUI-Datatables with a sleek outlined style

Check out the default UI from MUI-Datatables v4.3.0 here: https://i.stack.imgur.com/rbHgD.png I want to create a style similar to this: https://i.stack.imgur.com/AUHqC.png Just so you know, I am using the following packages: "@mui/material": &q ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Firefox seems to be the only browser where window.parent.document is functioning properly, as it is not working

Is there a way to update the value of a text box on the main page from an iframe? Currently, I have code that works in Firefox but not in Internet Explorer or Chrome. The "main.html" and "frame.html" files are located in the same directory. Any suggestions ...

Need a tool for validating forms?

I am currently facing some confusion with the UI Validation plugin that we are using. Within our application, we employ Spring MVC, Jquery & Bootstrap. As we delve into UI development, we have encountered uncertainty in selecting an appropriate Validation ...

What are the benefits of keeping JavaScript and HTML separate in web development?

Recently, I came across the concept of Unobtrusive JavaScript while researching best practices in the realm of JavaScript. One particular point that grabbed my attention was the idea of separating functionality (the "behavior layer") from a web page's ...

Tips for showcasing JSON data in AngularJS by utilizing the <pre> tag

How can I properly format and display a JSON string inside a dynamically created Div using a forEach loop? Here is my current code snippet: <div id="container_div"> </div> $scope.getJSON = () => { var settings = { "url ...

Unable to Remove parentNode Class

I'm looking to eliminate a class from the parent <span> of the current node, which I have named "rows". When I view rows.parentNode in the console, it shows DOMTokenList["checked"]. How can I go about removing the checked class from it? I attem ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

arrow function implemented in a React hook for handling onClick event

From my understanding, placing an arrow function in the JSX creates a new reference of a new function each time it is triggered. For example: <p onClick={() => handleClick() /> In older versions of React with classes, we could do this: <p onCl ...

Troubleshooting the image mapping issue in a React-based Netflix clone application

Currently, I am a beginner in coding and attempting to learn React. I decided to create a clone of Netflix but encountered an issue when trying to render images for different categories of movies. The browser is not displaying the images and the console is ...

Experiencing significant delays in keyboard response when using an Angular application on mobile browsers such as Safari

Experiencing a frustrating delay in keyboard response when using an Angular app on mobile Safari and Chrome. Surprisingly, there are no such issues when typing on desktop browsers. Any suggestions for troubleshooting this problem? My hunch is that it may ...

Encountering an Error with JsonRpcProvider while deploying a contract or attempting to run a node

An error has occurred: Error: ERROR processing skip func of /home/dylan/hh-fcc/hardhat-smartcontract-lottery-fcc/deploy/00-deploy-mocks.js: TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider') While following the freecodeca ...