var app = angular.module("myApp", []);
app.controller("myController", function ($scope) {
$scope.model = {
name: ""
};
});
app.directive("formGroup", function () {
return {
restrict: "C",
//get the controller in the link function
require: "formGroup",
link: function ($scope, element, attributes, controller) {
var errorList = {};
controller.inputError = function () {
element.addClass("has-error");
};
controller.inputValid = function () {
element.removeClass("has-error");
};
},
//the controller is initialized in link function
controller: function() {return {};}
};
});
app.directive("input", function () {
return {
restrict: "E",
//require controlllers of ngModel and parent directive
//formGroup
//they're injected as array parameter of link function
require: ["?ngModel", "^?formGroup"],
link: function ($scope, element, attributes, controllers) {
var modelController = controllers[0];
var formGroupController = controllers[1];
if (!modelController || !formGroupController) return;
var hasBeenVisited = false;
// check if user has left the field
element.on("blur", function () {
$scope.$apply(function () {
hasBeenVisited = true;
});
});
// Watch the validity of the input
$scope.$watch(function () {
return modelController.$invalid && hasBeenVisited;
}, function () {
// $emit messages to the control group
if (modelController.$invalid && hasBeenVisited) {
formGroupController.inputError();
} else {
formGroupController.inputValid();
}
});
}
};
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.