Pedro Henrique Pedro Henrique - 24 days ago 6
AngularJS Question

Work with ng-disable when required field is empty

I'm having some problems to put

ng-disable
to work, so, I have this div:

<div>
<p>{{ message }}</p>
<div >
<input type="number" id="field1" placeholder="field 1" ng-model="field1" min="0" required>
<input type="date" id="field2" ng-model="field2">
</div>
<button ng-disabled="field1.$valid" ng-click="submit()">OK</button>
</div>


I want to validate if the field1 is empty (not filled) I want to disable the button, so, the user can't click on it.

How I can do that?

I tried some ways, but anyone worked for me.

Answer

You should have your HTML code inside a form. Click on Run code snippet to see it working.

function ApplicationController($scope) {     
    $scope.message = "Hola Pedro Henrique!";
    $scope.submit = function(){
        console.log($scope.field1);
    };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app ng-controller="ApplicationController" role="form" name="form1" novalidate>
    <p>{{ message }}</p>
    <div>
        <input type="number" id="field1" placeholder="field 1" ng-model="field1" min="0" required>
        <input type="date" id="field2"  ng-model="field2">
    </div>
    <button type="submit" ng-disabled="form1.$invalid" ng-click="submit()">OK</button>
</form>