2015-06-19 42 views
2

時爲true。除非stuff []至少添加了一個項目,否則整個表單不應有效。當用戶在文本框中輸入一個值,然後單擊添加它,然後將值添加到stuff [],只有當此值已添加到stuff []時,如果啓用提交按鈕。但是,只要用戶在沒有點擊添加的情況下在文本框中鍵入任何內容,並且因此沒有東西[],它就會使表單有效並啓用提交按鈕。

<form ng-app="myApp" ng-controller="myCtrl" name="myForm" ng-submit="submit()" novalidate> 
    <div ng-repeat="things in stuff"> 
     <table><tr><td>{{things}}</td></tr></table> 
    </div> 

    <input type="text" name="app" ng-model="input" ng-required="!stuff[0]" /> 

    <button ng-disabled="!input" ng-click="add()"> 
     <span> add</span> 
    </button> 

    <input type="submit" value="Submit" ng-disabled="myForm.$invalid" /> 

    <script> 
     angular.module('myApp', []).controller('myCtrl', function ($scope) { 
      $scope.stuff = []; 
      $scope.input = null; 

      $scope.add = function() { 
       var l = $scope.stuff.length; 
       $scope.stuff[l] = $scope.input;    
       $scope.input = null; 
      }; 
      $scope.submit = function() {};    
     }); 
    </script> 
</form> 

回答

1

[編輯] 直接回答你的問題:!stuff[0]爲TRUE時沒有什麼數組中的,否則返回FALSE。當它爲TRUE時,則需要輸入,使表單'初始'無效。只要您在輸入中輸入了某些內容,現在就滿足了這個要求,這意味着該表單有效,現在您可以單擊提交按鈕。這個條件實際上與將某些東西放入數組無關。

這是可以通過附加一個條件到stuff.length,我的答案建議下面。它不會使表單無效(您可以輕鬆地在其他地方使用此條件),但它至少會禁用提交按鈕。

我不明白你爲什麼需要ng-required,因爲你想禁用提交按鈕,這意味着邏輯應該附加到提交按鈕,而不是輸入文本框。

我會做這個:

<input type="text" name="app" ng-model="input"/> 

<button ng-disabled="!input" ng-click="add()"> 
    <span> add</span> 
</button> 

<input type="submit" value="Submit" ng-disabled="stuff.length == 0" /> 

如果沒有什麼東西,這將禁用提交按鈕。