2

I have an input type number. I want to set default value 1 if ng-model is null or empty or undefined. it works fine. But on the same page, I have a submit button. on click of this button, I'm just returning false for some validation fail. But when it returns after validation fails. my dropdown (input type number) shows empty value. I check the value of ng-model, it's empty.

So if the value is not a proper number, I want it to set to 1 by default.

<input type="number" step="1" min="1" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? '': event.charCode >= 48 && event.charCode <= 57" id="train_n_file" 
                                          ng-init="item.n_fold = item.n_fold || 1" ng-model="item.n_fold" ng-disabled="item.train_select=='training_time_range'" style="margin-top: -2px;" class="input-div" value="{{1}}">


<md-button ng-click="schedule_event()" type=submit id="step-btn" class="build-model md-raised step-btn md-primary md-button md-ink-ripple"> Schedule </md-button>


 $scope.schedule_event = function () {
  if (some condition) {
      $scope.showAlert('Please pick schedule frequency.');
      return false;
  }
3
  • Why do you have that onkeypress in there? Setting type="number" prevents entry of non-numeric values. You also shouldn't have a value attribute if you're using ng-model. Sounds like most of this should be handled in your model or controller. Commented Jun 14, 2017 at 20:40
  • @MikeMcCaughan I was just trying everything to get it done Commented Jun 14, 2017 at 20:41
  • Try creating a directive which checks the <input> field value ,do the necessary validation and updates the model value of <input> field. Commented Jun 15, 2017 at 7:06

1 Answer 1

2

Edited:

This would do the trick. ng-init is used to initialize values for the ng-model.

var app = angular.module('myApp', []);

app.controller('inputCtrl', ['$scope', function($scope) {
  $scope.item = undefined;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>plnkr</title>

  <body ng-app="myApp">
    <div class="row">
      <div ng-controller="inputCtrl">
        <input type="number" step="1" min="1" ng-model="item" ng-init="item = 10" />
      </div>
    </div>

    <script src="inputCtrl.js"></script>

  </body>

</html>

Sign up to request clarification or add additional context in comments.

3 Comments

Edited. Added variable to ng-init.
try by adding a submit button, try to reproduce the same scenario. u will get my question
Please provide a plunker with the scenario, we will get your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.