AngularJS - Basic

Forms in Angular

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>
        
        <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"  />
            </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" ng-model="item.duedate" name="duedate" class="form-control" />
            </div>
            
            <div class="form-group">
                <label>Urgent 
                    <input type="checkbox" name="is_urgent" ng-model="item.is_urgent" />
                </label>
            </div>
            
            <button type="submit" class="btn btn-default">Submit</button>
            
        </form>
        
    </div> 
    
</div>

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;
}

JavaScript

/**
 * $scope App
 */
var myApp = angular.module('myApp', []);

myApp.controller('MainCtrl', ['$scope', function($scope) {
    
    $scope.data = {
        items: []
    };
    
    // 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);
        
    };*/
    
}]);