Jashaszun Jashaszun - 1 year ago 45
AngularJS Question

How do I require multiple input fields in AngularJS?

I'm trying to write a simple page with a couple of inputs which should be

to not be empty.

Here's the code to do that (self-contained):

<!DOCTYPE html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
var app = angular.module("myApp", []);
app.controller('myController', ['$scope', function($scope) {
input.ng-invalid {
background-color: pink;
input.ng-valid {
background-color: lightgreen;
<body ng-app="myApp">
<div ng-controller="myController">
Description: *<input type="text" id="input-description" ng-model="req-text" required></input><br/>
Order: *<input type="number" id="input-order" ng-model="req-number" value="100" step="100" required></input><br/>

What I was hoping it would do is start with the text field being blank and red (invalid), and the number field being
and green (valid).

The first thing I tried was setting both
s for the inputs to the same thing, but that caused the number field to update the text field when it was updated (but not the other way around).

Since that obviously didn't work, I tried using different models for the inputs, as shown in my code. However, now both inputs have a value of
(even the text field, which should still be blank), and both inputs cannot be typed into or otherwise edited.

What am I doing wrong, and how do I just get both inputs to be
separately by Angular?

Answer Source

What you're doing wrong first of all is using illegal identifiers for models. req-number is not a valid identifier for a variable. (remember all of these models are actually refered as $scope.variableName, imagine $scope.req-number). Hence your inputs are made readonly. You can actually see that when you examine console of your browser.

Second, html attribute value is ignored for input in this case. Use ng-init instead to initiate the model with the value desired.

    <div ng-controller="myController">
        Description: *<input type="text" ng-model="req_text" REQUIRED><br/>
        Order: *<input type="number" ng-model="req_number" ng-init="req_number=100" required><br/>

Plunker with correct code

PS and a small remark, closing tags are ignored for <input>