Base ng-disabled on input rather than form

I want to disable a button next to my input box if that input is $invalid. If I was disabling this button based on the validity of an entire form I would simply use ng-disabled="formName.$invalid". How would I accomplish the same task but based on just one input field?

<td>
  <input type="number" min="0" ng-model="points.limit">
</td>
<td>
  <button class="btn btn-limit btn-success" ng-click='points.setLimit(points.limit)' ng-disabled="?">Save</button>
</td>

Answers:

Answer

You need to specify name attribute for ng-model="points.limit" element so that it would be have an part of formName. Also after declaring the name attribute on element you could have access to that form element using formName.limit, You could also get this object inside a scope.

Markup

<td>
    <input type="number" name="limit" min="0" ng-model="points.limit">
</td>
<td>
    <button class="btn btn-limit btn-success" ng-click='points.setLimit(points.limit)' 
     ng-disabled="formName.limit.$invalid">
      Save
    </button>
</td>
Answer

Give the input a name like so:

<input name="limit" type="number" min="0" ng-model="points.limit">

and then you can disable the button like so:

<button class="btn btn-limit btn-success" ng-click='points.setLimit(points.limit)' ng-disabled="theForm.limit.$invalid">Save</button>

Answer

Since the model's value becomes undefined when it is invalid, one solution would be to use that to determine validity since you aren't using a form.

var app = angular.module('myapp', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myapp">
  <body>
    <input name="abc" type="number" min="0" ng-model="points.limit">
    <button ng-click='points.setLimit(points.limit)' ng-disabled="points.limit === undefined">Save</button>
  </body>
</html>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.