简体   繁体   English

AngularJS-检查类型为“数字”的输入是否具有值,0为有效值

[英]AngularJS - Check if an input of type “number” has a value, 0 being a valid value

I am struggling to get AngularJS to work properly with a small thing that I am trying to implement. 我正在努力使AngularJS在我尝试实现的一件小事情上正常工作。

I have an input of type number (which likely causes the issue) which is bound to a variable in my controller, and I need to disable a button if this input is empty. 我有一个类型为number的输入(可能会导致问题),该输入已绑定到控制器中的变量,并且如果此输入为空,则需要禁用按钮。

Here's the code for my input and button: 这是我的输入和按钮的代码:

<input type="number" min="0" max="20" ng-model="student.mark">

<button ng-disabled="!student">Send</button>

I tried several solutions to disable my button if the field is empty, but enable it if it has a value of 0 : 我尝试了几种解决方案来在字段为空的情况下禁用我的按钮,但是在其值为0其启用:

<button ng-disabled="!student || !student.mark">Send</button>

<button ng-disabled="!student || !angular.isNumber(student.mark)">Send</button>

<button ng-disabled="!student || student.mark == ''">Send</button>

<button ng-disabled="!student || student.mark === ''">Send</button>

None of those seem to work. 这些似乎都不起作用。 It will work properly if I have any number in my input, but either the button will be disabled if I have the value "0", or the button will stay enabled if I put a valid value and then remove it. 如果我在输入中输入任何数字,它将正常工作,但是如果我输入的值为“ 0”,则该按钮将被禁用,或者如果我输入了一个有效值然后将其删除,则该按钮将保持启用状态。

What makes me think that it should work is the fact that if I display the value using {{ student.mark }} , the value 0 will indeed show as "0" and an empty input will show as empty. 我认为应该起作用的原因是,如果我使用{{ student.mark }}显示值,则值0的确会显示为“ 0”,而空的输入将显示为空。

Thanks. 谢谢。

NOTE : 0 is treated as false. 注意:0被视为错误。

In your controller define 在您的控制器中定义

 $scope.student.mark = null;

Use condition 使用条件

 ng-disabled="student.mark == null && student.mark < 0"

I would suggest you to use form for that, something like that: 我建议您使用表格,例如:

<form name="formName" ng-submit="someMethod(student)" autocomplete="off" 
novalidate>

<input type="number" min="0" max="20"
    ng-model="student.mark" placeholder="e.g. 12"
    ng-required="true" /> 
<button type="submit" value="Send" ng-disabled="formName.$invalid || <something else here>" />
</form>

我尝试了更多操作,然后实际测试了该值是否为null达到了目的:

<button ng-disabled="!student || student.mark === null">Send</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM