AngularJS如果值在数组中,则输入有效

时间:2017-06-14 08:26:44

标签: angularjs validation angular-validation

有输入

<div ng-app="myApp" ng-controller="myCtrl">
    <form>
        <input type="number" ng-model="$ctrl.myNumber" />
    </form>
</div> 

如果输入值是数组中包含的任何数字(在此示例中为数组possibleInputValues),我希望它有效。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    var self = this;
    self.possibleInputValues = [1, 2, 3, 4, 7, 8, 9, 10];
});

因此,例如,如果用户键入&#39; 2&#39;在输入中,它应该是有效的(因为数组possibleInputValues包含2),但是对于值5应该是无效的。

我在AngularJS Documentation中找到的一种方法是为这种验证编写自己的指令。这是唯一的方法还是有更轻量级的方式呢?

我正在寻找的是这样的

<input type="number" ng-model="$ctrl.myNumber" valid-if="$ctrl.isInMyArray()"/>

和控制器

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;
    }
});

1 个答案:

答案 0 :(得分:1)

查看包含Angular-UI's projectui-validate/ui-validate-async directives

此指令使创建自定义验证程序表达式变得非常容易。在您的情况下,它看起来像ui-validate="{inArray: 'isInMyArray($value)' }"