Reputation: 260
I'm trying to use a form within a component in Angular 1.5
I have the form working, in that I have model binding and can get to the data on submit. So I'm 90% of where I want to be, what's missing is being able to reset the form correctly using $setPristine.
I've attempted a couple of approaches the first was passing in the form as an argument to the reset function.
form.html
<form name="$ctrl.userForm">
...
<input class="btn btn-default" type="button" ng-click="$ctrl.reset($ctrl.userForm)" value="Reset" />
</form>
form.component.js
ctrl.reset = function(userForm) {
ctrl.user = {};
userForm.$setPristine // Cannot read property '$setPristine' of undefined
};
I also tried declaring $ctrl.userForm as an empty object $onInit, but that didn't seem to work either. With the $setPristine line removed the reset works in clearing the forms data but not it's state from an angular perspective.
Any ideas on what I'm missing?
Upvotes: 2
Views: 665
Reputation: 9810
From your plunkr you have the entire component declared bellow.
function formController() {
var ctrl = this;
...
ctrl.reset = function(userForm) {
ctrl.user = {};
userForm.$setPristine
};
ctrl.reset();
}
The error is originated from this line ctrl.reset();
where you call the method without sending the argument userForm
. Also, you are using $setPristine
in the wrong way and you don't have to pass the form as an argument either.
I sugest you to use the form declared on your controller like so:
angular
.module('application')
.component('mkForm', {
templateUrl: 'form.html',
controller: formController
});
function formController() {
var ctrl = this;
ctrl.master = {};
ctrl.update = function(user) {
ctrl.master = angular.copy(user);
};
ctrl.reset = function() {
ctrl.user = {};
ctrl.userForm.$setPristine();
};
}
Note: you don't have to call
ctrl.reset();
because the pristine state is the default state.
Upvotes: 3