Don't record invalid values with ng-model

前端 未结 3 1798
陌清茗
陌清茗 2020-12-18 00:08

I really like how the ng-model attribute binds directly to my model and users get instant feedback on their changes. For my use case that\'s perfect. However, I don\'t wan

相关标签:
3条回答
  • 2020-12-18 00:37

    I believe the default behaviour of AnugularJS validators are not to update the model if the value passed is invalid. If you look at the developer guide and go through Custom Validation these samples also show that the model is not update or is cleared on invalid value provided in the UI

    0 讨论(0)
  • 2020-12-18 00:39

    As Chandermani said, it is the default behavior, here is a example that shows it in action :

    <form name="myform">
        <input type="text" name="myinput" ng-model="myvalue" ng-minlength="4" required>
    </form>
    
    Is the input valid ? {{ myform.myinput.$valid }} <br />
    Input's value : {{ myvalue }}
    

    {{ myvalue }} doesn't show anything until you write at least 4 characters in the input.

    Best Regards.

    EDIT

    If you need a default value, I guess you could break down your value into 2 values, using a computed value :

       var validNumber = 15;
        $scope.validNumber = function () {
            if ($scope.myform.myNumber.$valid) return $scope.myNumber;
            else return validNumber;
        };
    

    I set up an example here : http://jsfiddle.net/7vtew/1/

    0 讨论(0)
  • 2020-12-18 00:39

    This is default behaviour, but, you can modify this using ngModelOptions directive

    <input 
        type="number"
        ng-model="validNumber"
        required
        min="10"
        max="20" 
        ng-model-options="{ allowInvalid: true }"
        />
    

    Documentation: https://docs.angularjs.org/api/ng/directive/ngModelOptions See the section 'Model updates and validation'

    0 讨论(0)
提交回复
热议问题