Skip to content Skip to sidebar Skip to footer

AngularJS Comparing $viewValue Against Ng-model Or Object Param

I have a dynamic form that utilizes ng-min/ng-max for validation. My ng-max & ng-min are bound to object parameters modelParam.maxvalue and modelParam.minvalue, respectively.

Solution 1:

Remember that the $viewValue is for a particular ngModel instance. Its not a generic value. For example if you had multiple inputs, each would have its own $viewValue. Therefore in the span element you need to specify which ngModel you are referring to. An easy way to do this in the view itself is to use the name attributes of the form and input field. Also remember that in the case of an input, the $viewValue is a string, so when comparing it to min and max value, you need to use its length property. Take a look at the updated code to reflect these changes:

<ng-form name="modelParamsFieldForm">
    <label class="col-md-5">{{ modelParam.paramname }}</label>              
    <input type="number" class="form-control input-sm col-md-5" ng-
        model="modelParam.value" name="value" ng-min="modelParam.minvalue" 
        ng-max="modelParam.maxvalue" required style="maxhight: 20px">
    <span ng-show="modelParamsFieldForm.value.$invalid"></span> 
    <span ng-if="modelParamsFieldForm.value.$viewValue.length > modelParam.maxvalue">Error message</span>
    <span ng-if="modelParamsFieldForm.value.$viewValue.length < modelParam.minvalue">Error message</span>
</ng-form>

UPDATE

jsfiddle with a working example: here


Post a Comment for "AngularJS Comparing $viewValue Against Ng-model Or Object Param"