Mr. Developer Mr. Developer - 7 months ago 141
Javascript Question

How can i compare two numbers inside input field using angularjs?

I'm trying to match two randomly generated numbers. I want to add

ng-invalid
class if result wrongly enter. In the controller this function is generating the numbers.

AngularJs



$scope.getRandomSpan = function(){
return Math.floor((Math.random()*6)+1);
}


HTML



<span ng-init="a=getRandomSpan()">{{ a }}</span>
<span ng-init="b=getRandomSpan()"> + {{ b }}</span>


I want to validate the numbers once user enter number in input field.

<input type="number" ng-model="captcha" required />


For example function generate two numbers 2 and 3
(equal to 5)
, now i want to add
ng-invalid
class if entered number not equal to 5. I have done this task in the controller which is validating after submit the form.

var random = $scope.a + $scope.b;
var enteredcaptcha = $scope.captcha;
if(random == enteredcaptcha){...}


But i don't know how to validate on the spot, can any one guide me about this I will appreciate. Thank You

Answer

i have updated my code and it will display message if you enter correct value otherwise nothing happen

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.getRandomSpan = function() {
    return Math.floor((Math.random() * 6) + 1);
  }
  $scope.$watch("captcha", function() {
    var random = $scope.a + $scope.b;
    var enteredcaptcha = $scope.captcha;
    if (enteredcaptcha) {
      var myEl = angular.element(document.querySelector('#ans'));
      if (random == enteredcaptcha) {
        myEl.addClass("ng-valid").removeClass("ng-invalid");
      } else {
        myEl.addClass("ng-invalid").removeClass("ng-valid");
      }
    }
  });
});
#ans {
  display: none;
}

.ng-invalid{
  display:none !important;
}

.ng-valid{
  display:inline-block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <span ng-init="a=getRandomSpan()">{{ a }}</span>
  <span ng-init="b=getRandomSpan()"> + {{ b }}</span>
  <input type="number" ng-model="captcha" />
  <span id="ans">excellent!!!!</span>
</div>