AngularJS provides what they call 'model flags' on their forms. For example, you can have formName.$dirty, formName.$invalid, etc. What I want to know is how can I create my own custom flag for my AngularJS forms? A high level demonstration or link to an article would be a sufficient answer.
Asked
Active
Viewed 600 times
0
-
The formName is a standard javascript object (FormController to be precise), which you can add properties as you want. – Chandermani Nov 19 '14 at 15:12
-
Thinking of formName as an instance of FormController is definitely getting me in the right direction. Could you show me a way to updated the formName object via a custom validation directive? For example, could I have a directive using ng-model that sets `formName.$warning` when someone types 'bad speling' into the input? – Adam Waselnuk Nov 20 '14 at 14:42
1 Answers
0
See here: how-to-add-custom-validation-to-an-angular-js-form.
In short, this is a custom valitation directive example:
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var blacklist = attr.blacklist.split(',');
// for DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var valid = blacklist.indexOf(value) === -1;
ngModel.$setValidity('blacklist', valid);
return valid ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
return value;
});
}
};
});
And this it's an example of it's usage:
<form name="myForm" ng-submit="doSomething()">
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
<span ng-show="myForm.fruitName.$error.blacklist">
The phrase "{{data.fruitName}}" is blacklisted</span>
<span ng-show="myForm.fruitName.$error.required">required</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
But, again, read the referenced question and accepted answer, it's by far more complete...
-
That's not quite what I was looking for. I want to know how to modify the validity state of the entire form. For example, if someone were to enter a blacklisted fruit, would I be able to set the form controller state to `myForm.$hasBlacklist`? – Adam Waselnuk Nov 20 '14 at 14:39