AngularJS - Basic
Forms validation and state
by Ryan Morris
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<div class="container" ng-app="myApp">
<div ng-controller="MainCtrl">
<h1>Forms</h1>
<p ng-show="itemForm.$pristine">
This form is clean and green.... and pristine
</p>
<div ng-show="data.items.length">
<p>To do items:</p>
<ul>
<li ng-repeat="item in data.items">
{{item.title}}
<!-- Ability to remove an item from the list
<a href="#" ng-click="removeItem($index)">Remove</a>
-->
</li>
</ul>
</div>
<form name="itemForm" ng-submit="submitForm()">
<div class="form-group">
<input type="text" ng-model="item.title" name="title" placeholder="Title" class="form-control" required ng-minlength="3" />
<span ng-show="itemForm.title.$invalid">
This title is not valid.
</span>
<span ng-show="itemForm.title.$error.required">
Please enter a title.
</span>
<span ng-show="itemForm.title.$error.minlength">
Title must be at least 3 characters long.
</span>
</div>
<div class="form-group">
<label>Description</label>
<textarea ng-model="item.description" name="description" class="form-control" ></textarea>
</div>
<div class="form-group">
<label>Due on</label>
<input type="date"...
CSS
div[ng-controller] {
border: 1px solid #ccc;
border-radius:5px;
margin:5px 0;
padding:5px;
}
div[ng-controller] > div[ng-controller] {
background-color:#f0f0f0;
}
.ng-dirty .ng-invalid{
border:1px solid red;
}
.form-group span{
color:red;
}
.ng-pristine span{
display:none; /* force hides */
}
.ng-dirty.ng-invalid-required{
background-color:lightpink;
}
.ng-dirty.ng-valid{
border-color:green;
}
JavaScript
/**
* $scope App
*/
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', function($scope) {
$scope.data = {
items: []
};
/*// To enable the categories field
$scope.categories = [
{
id: 1,
name: "Work"
},
{
id: 2,
name: "Personal stuff"
},
{
id: 3,
name: "Chores"
}
];
*/
// form submission handler
$scope.submitForm = function() {
// angular automatically set up "item" in $scope
// it is also available via "this.item"
console.log("Submitting", $scope.item);
// add new todo item
$scope.data.items[$scope.data.items.length] = $scope.item;
// flush the form
$scope.item = {};
}
/*// Ability to remove an item from the list
$scope.removeItem = function(index) {
$scope.data.items.splice(index, 1);
};*/
}]);