【问题标题】:Angular Form Validation, Save button always disabledAngular 表单验证,保存按钮始终禁用
【发布时间】:2016-01-03 22:44:21
【问题描述】:

我有一个角度形式,其中问题在数组中指定。

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

});

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

例如:Disable a button if at least one input field is empty using ngDisabled

我做错了什么?

另外,有什么方法可以改进这段代码吗?这是我第一次尝试 Angular。

【问题讨论】:

  • 嗯,它确实有效。当所有输入都有效时,按钮不再被禁用。你使用哪个版本的 Angular?
  • 将此添加到表单的末尾&lt;pre&gt;{{ newSupplierForm.$error | json }}&lt;/pre&gt;。它会显示表单的错误。
  • 已修复 - 我做错了其他事情。傻我。

标签: javascript angularjs forms validation


【解决方案1】:

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

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


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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2020-02-12
    相关资源
    最近更新 更多