Having an input
<div ng-app="myApp" ng-controller="myCtrl">
<form>
<input type="number" ng-model="$ctrl.myNumber" />
</form>
</div>
I want it to be valid, if the input value is any number contained in an array (in this example the array possibleInputValues
).
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var self = this;
self.possibleInputValues = [1, 2, 3, 4, 7, 8, 9, 10];
});
So, for example, if the user types '2' into the input, it should be valid (as the array possibleInputValues
contains 2), but should be invalid eg for the value 5.
One way i found in the AngularJS Documentation is to write a own directive for this kind of validation. Is this the only way or is there a more lightweighted way to do so?
What I am looking for is something like this
<input type="number" ng-model="$ctrl.myNumber" valid-if="$ctrl.isInMyArray()"/>
and the controller
app.controller('myCtrl', function($scope) {
var self = this;
self.possibleInputValues = [1, 2, 3, 4, 7, 8, 9, 10];
self.isInMyArray = function(val) {
if (self.possibleInputValues.indexOf(val) !== -1) {
return true
}
return false;
}
});
Check Angular-UI's project which includes ui-validate/ui-validate-async
directives.
This directives makes it very easy to create custom validator expressions. In your case it can look like ui-validate="{inArray: 'isInMyArray($value)' }"
.