AngularJS。输入无效时需要禁用按钮

时间:2018-05-16 14:49:15

标签: javascript html angularjs forms validation

我是AngularJS的新手,当输入字段中的文本长度超过时,我需要禁用提交按钮。我根据左边的符号进行了ng-class赋值,但即使输入无效,form也有一个类有效,但是如何? 这是我的代码示例。

//Main file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="../lib/angular.min.js"></script>

<style type="text/css">
    ol {
        margin: 20px 0;
        padding: 20px;
    }

    input.ng-dirty.ng-invalid {
        border: 1px solid red
    }
</style>
</head>
<body ng-app="ngrepeatApp" ng-controller="ngrepeatCtrl">
<div class="container">
    <form novalidate name="paramForm">
        <div class="form-group" ng-repeat="p in params">
            <label>{{p.Title}}</label>
            <input type="text" class="form-control" placeholder="{{p.Description}}" required ng-model="p.Value" ng-class="(lengthDifference(p) < 0) ? 'ng-invalid':'ng-valid'">
            <small class="form-text text-muted">Available <span>{{lengthDifference(p)}}</span> symbols</small>
        </div>
        <button type="submit" class="btn btn-success" ng-disabled="paramForm.$invalid">Submit</button>
    </form>


</div>


<script src="app.js"></script>


</body>

</html>

和带有返回长度的函数的简单控制器

var app = angular.module("ngrepeatApp", []);

app.controller("ngrepeatCtrl", function ($scope) {

$scope.lengthDifference=function(p){
    var left =  p.MaxLength - p.Value.length ;
    return left;
};

$scope.params = [
    {
        Title: "Title",
        Description: "Type Title Here",
        Value: "",
        MaxLength: 10
    },
    {
        Title: "DisplayName",
        Description: "Type Title Here",
        Value: "",
        MaxLength: 15
    },
    {
        Title: "Category",
        Description: "Type Category Here",
        Value: "",
        MaxLength: 6
    }
];

});

感谢您的回答

0 个答案:

没有答案