Angular Bootstrap Control Group

http://angularjs.org/

by Martin Večeřa

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-controller="myController">
    <form name="myForm">
        <div class="form-group">
            <label class="control-label">Enter your name:</label>
            <input type="text" class="form-control span2" name="name" ng-required="true" ng-model="model.name" placeholder="Lowercase only" ng-pattern="/^[a-z]*$/" />
        </div>
    </form>Debug:
    <dl> <dt>model.name</dt>

        <dd>Name: {{model.name}}</dd> <dt>Form Valid:</dt>

        <dd>{{myForm.$valid}}</dd> <dt>Field Valid:</dt>

        <dd>{{myForm.name.$valid}}</dd>
    </dl>
</div>

JavaScript

var app = angular.module("myApp", []);
app.controller("myController", function ($scope) {
    $scope.model = {
        name: ""
    };
});

app.directive("formGroup", function () {
    return {
        restrict: "C",
        link: function ($scope, element, attributes) {
            var errorList = {};
            $scope.$on("inputError", function () {
                element.addClass("has-error");
            });
            $scope.$on("inputValid", function () {
                element.removeClass("has-error");
            });
        },
        //own scope, so emitted messages don't get mixed up
        scope: true
    };
});

app.directive("input", function () {
    return {
        restrict: "E",
        //require the access to the controller of ngModel
        //its injected as the 4th parameter of link function
        require: "?ngModel",
        link: function ($scope, element, attributes, modelController) {
            if (!modelController)
                return;
            // Watch the validity of the input
            $scope.$watch(function () {
                return modelController.$invalid;
            }, function () {
                // $emit messages to the control group
                if (modelController.$invalid) $scope.$emit("inputError");
                else $scope.$emit("inputValid");
            });
        }
    };
});