简体   繁体   中英

Get length of input type=“number” angularJS

So I have seen a lot of answers but none that fits my case. I cannot use jQuery fyi.

<ng-repeat="stuff in junk">
  <md-input-container>
    <input type="number" ng-model="stuff.value.currentValue" ng-keypress="myController.checkLength(stuff.length)"

This is obviously a very rough mockup of what im doing. Ultimately I am just trying to make a numeric input where i can limit the length and not just have an error telling them too many chars, on submission. Because the model is variable I cannot getelementbyID, cannot use maxlength as its type="number", etc. etc. I'm thoroughly stumped. I would really like to not use a standard input and then do validation on the user input but im out of ideas

您应该使用属性max ,在这种情况下应该可以使用。

<input type="number" max="9000" ng-model="stuff.value.currentValue" ng-keypress="myController.checkLength(stuff.length)" />

If I understand the question correctly, you're trying to set a hard limit on each input's length as the length of each stuff.value.currentValue (which may be variable) in the ng-repeat. If this is correct, you could try the following:

<input type="number" 
 maxlength="{{::stuff.value.currentValue.length}}"  
 ng-model="stuff.value.currentValue" 
 ng-keypress="myController.checkLength(stuff.length)" />

The :: before the variable name in the binding indicates a one time binding , meaning the value is set after the first digest cycle, and does not change after subsequent digests. This means that as your ng-repeat is looping through the data (say the words 'Peter', 'Paul', and 'Mary'), each input's maximum length will be the length of that original input (in this case, 5, 4, and 4), and will not change when the model is updated. The maxlength attribute will not provide an error message, but will not allow users to enter text that is longer than the original length of each stuff.value.currentValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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