NG-show does not function properly with Angular validation messages when there are two input fields present

I have created a form with two modes: 'Create' and 'Edit'. Depending on the mode selected, specific div content is displayed in different areas of the layout. The content of the div includes an input field and validation messages related to that input.

Here's an example for better understanding:

View:

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
   <form name="editForm">
     <div ng-show='mode == "Edit"'>
       <div class="form-group" ng-class="{true:'has-error',false:''}[editForm.FirstName.$valid === false && editForm.FirstName.$dirty]">
          <input type="text" ng-model="foo" ng-maxlength="5" name="foo" required />
          <div class="help-block" ng-messages="editForm.foo.$error" ng-if="editForm.foo.$dirty">
            <p ng-message="required">Required</p>
            <p ng-message="maxlength">Too long</p>
          </div>
       </div>
     </div>
     <div ng-show='mode == "Create"'>
       <div class="form-group" ng-class="{true:'has-error',false:''}[edit.foo.$valid === false && edit.foo.$dirty]">
          <input type="text" ng-model="foo" ng-maxlength="5" name="foo" required />
          <div class="help-block" ng-messages="editForm.foo.$error" ng-if="editForm.foo.$dirty">
            <p ng-message="required">Required</p>
            <p ng-message="maxlength">Too long</p>
          </div>
       </div>
     </div>
   </form>
      <div>
      Mode: {{mode}} <br>
      Value: {{foo}} <br>
      Is form valid: {{editForm.foo.$valid}} <br>
      </div>
  </div>
</div>

Controller:

var myApp = angular.module('myApp',['ngMessages']);

myApp.controller('MyCtrl',function($scope){
    $scope.mode = 'Edit';
});

Check out this JSFiddle for a working example.

The issue I'm facing is that the validation messages only display properly when the last input is shown. In Edit mode, even though it's the same input, the messages do not show correctly.

Answer №1

Swap out ng-show for ng-if directive.

When using ng-show, both div elements are rendered by the browser, but one has the ng-hide class if the ng-show expression evaluates to false.

On the contrary, with ng-if, the div element is not rendered at all if the ng-if expression is false.

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

How can elements be collapsed into an array using the Reactive approach?

Consider this TypeScript/Angular 2 code snippet: query(): Rx.Observable<any> { return Observable.create((o) => { var refinedPosts = new Array<RefinedPost>(); const observable = this.server.get('http://localhost/ra ...

Looping through a JSON array and encoding it using the `

I am looking to retrieve data from the database using AJAX and populate a 'select' tag with that data. Each name should be displayed in its own 'option'. Here is the code snippet: Index.php: <label>Select:</label> <sel ...

transferring information from the Quill text editor to the Node.js server

Is there a way to send data from Quilljs on the frontend to node.js on the backend? I've been searching for examples, but haven't found anything related to the backend. I tried reading the documentation for Quilljs, but I'm still struggling ...

Find out whether the object is located behind another item

Is there a method to determine if elementA is "obscured" by another element, meaning it is not visible to the user? We could potentially achieve this using stacking context, but the challenge lies in identifying which elements to compare. This would requi ...

Waiting for response in AngularJS Controller and setting callback

I have developed an AngularJS application with controllers.js and factories.js that I am excited about. However, I am facing a challenge when trying to manipulate the values within the controller (retrieved from the factories). The issue is that these val ...

Utilizing Ajax to dynamically load files within the Django framework

My current project involves working with Django, specifically a feature that requires loading a file and displaying its content in a textarea. Instead of storing the file on the server side or in a database, I am exploring the use of AJAX to send the file ...

Ways to extract only numbers from a string

I have encountered a frustrating issue in VueJS: I am receiving an object with the following structure: { "description": "this is our List.\n Our Service includes:\n-1 something\n-2 something else\n and another thing\n"}` My dile ...

Troubleshooting PHP/MySQL integration with Google Maps - issues persist

I have come across several other posts on this theme but unfortunately, none of them have been able to help me. I am using the article https://developers.google.com/maps/articles/phpsqlajax_v3, however, the code provided is not working for me. I have a fil ...

Intellij IDEA does not offer auto-completion for TypeScript .d.ts definitions when a function with a callback parameter is used

I've been working on setting up .d.ts definitions for a JavaScript project in order to enable auto-completion in Intellij IDEA. Here is an example of the JavaScript code I'm currently defining: var testObj = { tests: function (it) { ...

Leveraging an Angular directive callback to make updates to a bower package on a local

Currently, I am dealing with an issue related to an outdated bower package. There is a pull request available with the necessary code to fix my problem, but unfortunately it has not been approved yet. The solution involves just two lines of code, which I ...

Tips on accessing an AngularJS controller within a filter

Can dependency injection be utilized to access a controller within a filter? I attempted the following approach: app.filter('myFilter', function(MyCtrl) {...}) app.controller('MyCtrl', function(...) {}) However, an error is triggered ...

Uncovering the Image Orientation in Angular: Is it Possible to Determine the Direction Post-view or Upon Retrieval from Database?

I am currently working on creating centered and cropped thumbnails for images retrieved from a database. I came across some helpful information on how to achieve this: The resource I found is written for JavaScript, but I am using Angular 7. I am facing d ...

Troubleshooting scope evaluation in AngularJS within style tags on IE9 not functioning

My issue involves a div block with a style attribute that includes left:{{left}}px; and right:{{right}}px. Even though $scope.left and $scope.right are being updated, my item still doesn't move as expected. I have created a fiddle to demonstrate th ...

My goal is to exclusively create illustrations of items within a camera's view

Currently, I am using THREEJS to create a dynamically generated 'minecraft' world utilizing a perlin noise generator. Check out the progress so far: Block World Everything is going smoothly except that I am facing significant performance issues ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

Could you provide suggestions on how to update the content of an HTML tag within a Vue component?

I am new to Vue.js and struggling to grasp its concepts. I am interested in finding a way for my custom Vue component (UnorderedList) to manipulate the content within it. For example, if I have <p> tags inside my component like this : <UnorderedL ...

Hide a div in Angular if its sibling, which is being repeated, contains no elements after filtering

I am facing an issue with a structure I have, where I need to hide the divider when no elements are present inside the inner repeating div after being filtered based on certain conditions. <div ng-repeat="theme in myObj"> <div class="item ite ...

Stripping HTML elements from the body of an HTML document using AJAX before transmitting it as data to the controller

My JSP page contains two buttons labeled "download" and "sendemail". When the "Sendmail" button is clicked, an ajax method is triggered to generate a PDF version of the HTML body and send it to the back-end controller. I attempted to utilize the following ...

utilizing the target attribute within a form to open the link in the current page

I have been working on a web application and implemented a drop-down menu using a form to display information about the selected category. However, I noticed that when an option is selected, the link opens in a new window instead of the same window. Below ...

Mastering the art of throwing and managing custom errors from the server to the client side within Next.js

I'm in the process of developing a Next.js application and I am faced with the challenge of transmitting customized error messages from the server to the client side while utilizing Next JS new server-side actions. Although my server-side code is func ...