Having trouble getting AngularJS $setPristine to work with the controller as syntax?

When using $scope, $setPristine works fine, but when using 'controller as syntax' it doesn't seem to have the same effect

In View:

<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
    <form name="form1" id="form" novalidate>
        <input name="name" ng-model="first.data.name" placeholder="Name" required/>
        <button class="button" ng-click="first.reset()">Reset</button>
    </form>
    <p>Pristine: {{form1.$pristine}}</p>
    <p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr>

<h2>With $scope</h2>
<div ng-controller="SecondCtrl">
    <form name="form1" id="form" novalidate>
        <input name="name" ng-model="data.name" placeholder="Name" required/>
        <button class="button" ng-click="reset()">Reset</button>
    </form>
    <p>Pristine: {{form1.$pristine}}</p>
    <p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>

In app.js:

var app = angular.module('plunker', []);

app.controller('FirstCtrl', function() {
  'use strict';
  var vm = this;
  vm.data = { "name": ""};

    vm.reset = function() {
      vm.data.name = "";
      vm.form1.$setPristine();
    }
});

app.controller('SecondCtrl', function($scope) {
  'use strict';
  $scope.data = { "name": ""};

    $scope.reset = function() {
      $scope.data.name = "";
      $scope.form1.$setPristine();
    }
});

View the plunker example here: http://plnkr.co/edit/VcgZx3?p=preview

Answer №1

When utilizing the controller as syntax, it's important to note that the form and other attributes remain bound to the scope rather than the controller instance. Therefore, you will still need to employ $scope.form1.$setPristine(); to ensure the correct state of the form.

var app = angular.module('my-app', [], function() {})

app.controller('FirstCtrl', function($scope) {
  'use strict';
  var vm = this;
  vm.data = {
    "name": ""
  };

  vm.reset = function() {
    vm.data.name = "";
    $scope.form1.$setPristine();
  }
});

app.controller('SecondCtrl', function($scope) {
  'use strict';
  $scope.data = {
    "name": ""
  };

  $scope.reset = function() {
    $scope.data.name = "";
    $scope.form1.$setPristine();
  }
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>

<div ng-app="my-app">
  <h2>With Controller as Syntax</h2>
  <div ng-controller="FirstCtrl as first">
    <form name="form1" id="form" novalidate>
      <input name="name" ng-model="first.data.name" placeholder="Name" required/>
      <button class="button" ng-click="first.reset()">Reset</button>
    </form>
    <p>Pristine: {{form1.$pristine}}</p>
    <p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr/>

<h2>Using $scope</h2>
<div ng-controller="SecondCtrl">
  <form name="form1" id="form" novalidate>
    <input name="name" ng-model="data.name" placeholder="Name" required/>
    <button class="button" ng-click="reset()">Reset</button>
  </form>
  <p>Pristine: {{form1.$pristine}}</p>
  <p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
</div>

Answer №2

If you want to avoid using Arun's method of accessing the form through $scope, another option is to make sure the form can be accessed directly in the controller.

To achieve this, all you need to do is make a small change in your HTML when using the 'controller as' syntax. Update the form's name to include the controller object and update any references to the form in the template to include the controller variable:

   <h2>Using Controller as Syntax</h2>
<div ng-controller="SecondCtrl as second">
    <form name="second.form1" id="form" novalidate>
        <input name="name" ng-model="second.data.name" placeholder="Name" required/>
        <button class="button" ng-click="second.reset()">Reset</button>
    </form>
    <p>Pristine: {{second.form1.$pristine}}</p>
    <p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr>

Your JavaScript code will remain unchanged and continue to work as expected.

Answer №3

An alternative method that could make this task simpler is by passing the form controller as an argument to the reset() function:

…
<button class="button" ng-click="reset(form1)">Reset</button>
…

Then adjust the reset() function to utilize the provided parameter:

$scope.reset = function(form) {
  $scope.data.name = "";
  form.$setPristine();
}

Answer №4

To implement $setPristine without using $scope:

  <form ng-submit="$ctrl.save()" name="$ctrl.myForm">

In the controller:

var $ctrl = this;
 ...   
$ctrl.myForm.$setPristine();
$ctrl.myForm.$setUntouched();

This method has worked successfully for me. (Using AngularJS version 1.5.7)

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

Dealing with images on my live React application

For managing static images in my react app, I have integrated cloudinary as a CDN service. Can anyone suggest a seamless way to switch between using local image folders during development and switching to the CDN URL for production efficiently? ...

Failure to trigger custom event on FB pixel

I have installed the FB pixel helper browser plugin and I am confident that the FB pixel is properly implemented, as it is tracking pageviews correctly. However, I am facing an issue where the code for reporting a custom event is not working, even though ...

Prevent users from progressing to the next step without completing the form by implementing a feature in React

To ensure a seamless user experience, I am looking to implement a feature that disables the next button until all form fields are completed. The entire component is provided below for reference. The form utilizes the useFrom() function in react-hook-form ...

Removing one element from an array with mongoose

As a newcomer to web development, I am currently working on creating a todo app. Below is the schema and model that I have: const tdSchema = new mongoose.Schema({ category: { type: String, required: true, unique: true }, tds: { type: ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

Creating an interactive button using RichFaces and Bootstrap for seamless Ajax functionality

I have a challenge with making a fully clickable span or button that includes a Bootstrap refresh glyph-icon. The current code I have inherited only allows the icon itself to be clicked, leaving the area between the icon and button border unclickable. This ...

AngularJS: The $http.get request for JSON data from eBay is malfunctioning

I'm feeling lost and needing some guidance. When I make an ebay search request, the browser displays a JSON response. I saved this JSON in a file named v1 on my website. However, when I tried to access it through a $http.get request, it returned null. ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Can the break statement be used in jQuery or JavaScript?

I created a function that picks a text based on the input string. If there is a match, it sets it as selected. Here is the function: function chooseDropdownText(dropdownId,selectedValue,hfId){ $('#'+dropdownId+' option').ea ...

How to correctly pass values in AngularJS functions

Here is a function that takes a description variable as a parameter $scope.relsingle = function(description) { console.log(description); var url = $scope.url+'/api/descrelation?limit=4&description='+description; $http.get(url).su ...

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

`How can you utilize typeahead.js to showcase images on your webpage?`

Is there a way to show images using typeahead.js? I am attempting to include profile images in the list generated by typehead.js. Currently, I can only display text in the list as shown below: This is how my javascript appears: Along with my PHP code w ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Do you require API authentication for both the REST API and client running on the same server?

Let me give you an overview of the software we are working on: It's a web-based custom help desk application that requires users to log in using FOSUserBundle. Once logged in, they are directed to the dashboard where the frontend is built on AngularJS ...

Unable to successfully interact with Paypal button using selenium automation

I'm facing an issue with Selenium where I am unable to click on the PayPal button. https://i.sstatic.net/Xx62H.png https://i.sstatic.net/lZg88.png Despite trying various methods recommended in the Selenium documentation, the button remains unrespon ...

Issue: [$injector:unpr] Unidentified provider DictSrvProvider <- DictSrv <- MainCtrl

Encountering a puzzling error: Error: [$injector:unpr] Unknown provider: DictSrvProvider <- DictSrv <- MainCtrl Despite ensuring all dependencies are in order, and following the same method with another service and controller successfully. This is ...

Capturing and managing gulp-mocha error messages

For some reason, I just can't seem to get gulp-mocha to properly catch errors in my code. This issue is causing my gulp watch task to abruptly end whenever a test fails. My setup is incredibly basic: gulp.task("watch", ["build"], function () { gul ...

Each time I scroll, the object reloads itself

I am currently facing an issue with a 3D fridge model on my website. Despite successfully loading it, I am encountering a problem where the model refreshes every time it is dragged across the screen by the user scrolling. Please refer to the linked video f ...

Connect and interact with others through the Share Dialogues feature in the

Update - Edit I'm just starting to explore the concept of share dialogues and I want to integrate it into my website. On my site, there is a reaction timer game that shows the user's reaction time in seconds in a modal popup. I want users to be ...