Changing a field in AngularJS to set validity as true in a different way

After following the guidance provided in this answer to implement custom server-side validation for a unique email constraint, I encountered an issue with my submit function on the controller:

function submit(form){
  CompanyUser.save(vm.model)
      .success(function(data) {
          vm.closeModal();
          toastSucess(data);
      })
      .error(function(data) {
          if(data.code == 'error_duplicated_email')
              form['email'].$setValidity("uniqueEmail", false);
      });

}

The code above is related to handling the submission process, and below you can see my HTML code snippet dealing specifically with email validation:

<form name="form" novalidate ng-click="form.$valid && vm.submit(form)">
    <div class="form-group" ng-class="{ 'has-error': form.$submitted && form.email.$error.uniqueEmail }">
        <label>E-mail</label>
        <input type="email" class="form-control" name="email" ng-model="vm.model.email" required>
        <span ng-show="form.$submitted && form.email.$error.uniqueEmail" class="help-block">Duplicated e-mail</span>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-white" ng-click="vm.closeModal()">Cancel</button>
        <button type="submit" class="btn btn-primary">Save</button>
    </div>
</form>

Although everything works correctly when the server returns an error regarding duplicate emails, I faced a challenge when attempting to resubmit the form after changing the email. It seems that setting the validity to false prevents me from submitting again. How can I reset it to true to enable form submission?

Answer №1

If you want to reset a form to its original state, consider using the $setPristine(); method.

According to the angular documentation:

$setPristine(); Restores the form to its pristine state.

Upon calling this method, the form's $pristine state is set to true, $dirty state to false, ng-dirty class is removed, and ng-pristine class is added. It also sets $submitted state to false.

This action will affect all controls within the form as well.

Returning a form to a pristine state can be helpful when we need to 'reset' or 'reuse' the form after saving data or performing any other actions.

Answer №2

Check out the fix provided by @code90:

All I had to do was include ng-change="form.$valid=true" in the <input type="email"..

After making this adjustment, everything is working perfectly!

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

Intranet User Interface Developed with AngularJS

When utilizing ASP.Net Web API service, I am able to retrieve the current Windows user using the code snippet below. public class UserController : ApiController { public string Get() { var id = WindowsIdentity.GetCurrent(); retu ...

What is the best way to transfer response data from an http.get() request within an mdDialog to the main controller?

I am facing an issue with a mdDialog in my application where it calls an API and receives data that needs to be accessed in the main controller for another operation. CRUD operation $scope.add_id = []; $scope.createAddress = function() { $http.get(&a ...

Is the AngularJS email validation triggering too soon?

My challenge involves validating an email field in angularjs using the following code: <input type="email" ng-model="email" class="form-control" name="email" ng-required="true" placeholder="Email Address"> <span ng-show="loginForm.email.$touched ...

Is there a more efficient method for managing nested promises?

I am currently facing a challenge as a new developer. In the scenario I'm working on, there is a possibility of encountering a lock issue when the user saves their work. The user should be given an option to override the lock if it occurs. Since REST ...

AngularJS 1: Dynamically updating input values in real-time

Hey everyone, I'm experimenting with Angular and have encountered a roadblock. I am trying to assign values to an input element using ng-repeat for a list of parameters. <input type="text" ng-model="parameters.inParameterName" class="form-control ...

What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router. An error consistently arises ind ...

Integrating Angular Seed project with IntelliJ is a straightforward process that involves a

When attempting to add the Angular Seed project to IntelliJ, it consistently generates numerous separate modules. I simply desire a clear overview of the directory layout and don't want to deal with these module complexities. They just seem like unnec ...

Sending data to a server using the select element within a form

I am dealing with a controller that looks like this: $scope.disciplines = disciplines; $scope.discipline = disciplines[0]; This controller contains an array. Within my form, I have the following elements: <form class="form-horizontal" ng-submi ...

Issue with Angular UI tooltip not closing correctly inside ng-repeat loop

Check out the plunker link provided below for reference: http://plnkr.co/edit/RPpjULZsSDnTFPKiafl2 Essentially, I am experiencing an issue where the angular-ui tooltip persists even when moving to a position with ng-disabled set to true. Any suggestions ...

Challenges with managing controllers within Directives

Currently, I am in the process of updating some code within a personal project that utilizes Angular to adhere to best practices. I have come across suggestions that the future direction of Angular involves incorporating a significant amount of functionali ...

What is the procedure in AngularJS to obtain an ID from a URL? My current approach involves utilizing Restangular for communication with REST APIs

I have been successfully using Restangular to retrieve data from the backend. The URLs I was hitting used to provide the data in the following format: For example, when I hit http://mysite/responses/, the responses were in the following structure: [ ...

The server encountered an internal error when processing the Ajax request, causing it to

I encountered a 500 Internal server error with an angular ajax request. It is configured in Java Spring. Java: '@RequestMapping(method=RequestMethod.POST,value="setData") @ResponseBody public ModelClass setData(@RequestBody String value) { ...

The disabled attribute within a bespoke directive is not functioning as expected

I have been working on a custom directive that requires users to hold a button instead of just clicking it in order to reduce errors. Below the button, there is a material design slider indicating how long the user needs to hold the button. However, there ...

Angular's UI Modal: utilizing inline template and controller functionality

I am looking to create a simple confirmation box using UI-modal, which I have used successfully for more complex modals in the past that load their template and controller from external files. However, this time I want something even simpler - just a basi ...

When attempting to use the Angular $http.get method to connect to localhost, a 404 error is consistently returned

I am facing difficulties in creating a successful get request using Angular 1.2.13. var getProgress = function() { var promise = $http({method: 'GET', url: 'http://localhost:8080/project/local/some/getStatus'}); promise.t ...

Spin the AngularJS icon in a complete 360-degree clockwise rotation

Hey there! I'm new to Angular and I'm trying to create a button that will make an icon inside rotate 360 degrees when clicked. Right now, the entire button is rotating instead of just the element inside it. I want only the "blue square" to rotate ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Exploring AngularJS's Unique Features: Isolated Scope and Controller Connection

Currently, I am diving into Angular and endeavoring to develop a Phone Message Log application utilizing directives. The concept is simple - the user inputs a message, clicks a button, and it gets displayed in a "Message" log below. The challenge I'm ...

Unlocking CORS on DIVSHOT: A Step-by-Step Guide

I've encountered a challenge with the Access-Allow-Control-Origin issue while using Divshot. My mobile app is designed to display posts from a WordPress account, and while testing in a browser I can see the posts without any problem. However, when I t ...

Display the list in a grid format with 4 columns and x number of rows by utilizing Angular and Bootstrap

I need to display a list of values [1,2,3,4,5,6,7,8,9,10] as a bootstrap grid (class="col-x") using AngularJS. My goal is to create a grid with 4 columns and 3 rows from this list. Can you suggest the most efficient method to achieve this? ...