The $pristine
property is not set on your model ($ctrl.form
). It is actually set on the ngFormController
. However, in order to have it defined on your controller, you have to define the form name on your form tag like bellow:
<form name="$ctrl.form">
<div class="form-group">
<label for="name">Name</label>
<input ng-model="$ctrl.model.name" class="form-control" id="name" name="name" type="text" />
</div>
</form>
Notice that I changed ng-model="$ctrl.form.name"
to ng-model="$ctrl.model.name"
, because model is different than form controller. Therefore, your model has to be registered somewhere else.
Alternatively, you can use <div ng-form="$ctrl.form">
to bind the ngForm
directive in a different element than form
.
Finally, ngForm
will bind an ngFormController
into your controller (this
) so that you can have access to your pristine state inside your controller like the following snippet.
var _self = this;
_self.$postLink = function () {
angular.forEach(_self.form, function(value, key) {
if(key[0] == '$') return;
console.log(key, value.$pristine)
});
};
Notice that I used the _self.$postLink
hook, because the form will only be ready after the component link phase ended (it means child are fully linked to parent, hence postLink
).
You can check the full working snippet bellow:
angular.module('app', [])
.component('app', {
template: `
<form name="$ctrl.form">
<div class="form-group">
<label for="name">Name</label>
<input ng-model="$ctrl.model.name"
type="text"
class="form-control"
id="name"
name="name" />
</div>
</form>
`,
controller: function() {
var _self = this;
this.$postLink = function() {
angular.forEach(_self.form, function(value, key) {
if (key[0] == '$') return;
console.log(key, value.$pristine)
});
};
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<div ng-app="app">
<app></app>
</div>