Angular表单验证,保存按钮总是禁用的

Angular Form Validation, Save button always disabled

本文关键字:按钮 表单 验证 保存 Angular      更新时间:2023-09-26

我有一个有棱角的表单,其中问题在数组中指定。

HTML格式如下:

<form ng-controller="SupplierController" name="newSupplierForm">
  <p>Enter details for the new Supplier. The new supplier will be added to category {{selectedCategory.description}}</p>
  <p ng-repeat="field in formfields">
     <label class="field" for="{{field.name}}" ng-hide="newSupplierForm.{{field.name}}.$dirty && (newSupplierForm.{{field.name}}.$error.required || newSupplierForm.{{field.name}}.$invalid)">{{field.caption}}</label>
     <label class="error" for="{{field.name}}" ng-show="newSupplierForm.{{field.name}}.$dirty && (newSupplierForm.{{field.name}}.$error.required  || newSupplierForm.{{field.name}}.$invalid)">{{field.caption}}</label>
     <input type="{{field.type}}" name="{{field.name}}" ng-model="newSupplier[field.name]" ng-required="{{field.required}}">    
  </p>
  <button ng-disabled="newSupplierForm.$invalid" ng-click="saveSupplier()">Save</button>
</form>

控制器是:

financeApp.controller('SupplierController', function($scope, $http) {
$scope.formfields = [
    {caption:'Name :', name:'name', required:"true", type:"text"},
    {caption:'Address :', name:'address1', required:"true", type:"text"},
    {caption:' :', name:'address2', required:"true", type:"text"},
    {caption:' :', name:'address3', required:"", type:"text"},
    {caption:' :', name:'address4', required:"", type:"text"},
    {caption:'Post Code :', name:'postcode', required:"", type:"text"},
    {caption:'Email :', name:'email', required:"", type:"email"},
    {caption:'Phone :', name:'phone', required:"", type:"text"}
];
$scope.newSupplier = {};
$scope.saveSupplier = function() {
    $http.post('/finance/supplier', newSupplier).success(function(data) {
        alert(data);
    });     
}
});

这一切似乎都正常工作,除了保存按钮从未启用,即使表单是有效的。到目前为止,我所做的研究表明这应该是可行的,但事实并非如此。

示例:如果至少有一个输入字段为空,使用ngDisabled 禁用按钮

我做错了什么?

还有,有没有什么方法可以改进这段代码?这是我第一次尝试使用Angular。

试试不带花括号的ng-required="field.required",因为它已经需要一个角表达式。

在控制器内部,将required视为真或假,而不是字符串。


至于如何改进这一点,你使用的方法是可以的,但如果你的表单总是有相同的字段(它不是动态的),你应该为每个字段创建html元素,而不是在控制器中声明它们。

控制器应该控制视图的行为,而不是显示哪些字段(在非动态视图中)。