<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js" data-semver="1.4.7" data-require="angular.js@*"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="sampleDirective" ng-controller="MyModule">
<div>
<h3>Attribute Based Directive:</h3>
Enter Alphabet : <input type="text" alphabet /><br />
</div>
<div>
<h3>CSS Based Directive:</h3>
Enter Number: <input type="text" class="numeric" /> <br />
</div>
<div>
<h3>Element Based Directive:</h3>
Select a Value:<drop-down object="values"> </drop-down><br/>
Enter Value For Drop Down:<input type="text" ng-model="val" />
<button ng-click="add()">Add</button>
</div>
</body>
</html>
// Code goes here
var app = angular.module('sampleDirective', []);
app.controller('MyModule', function ($scope) {
$scope.values = ["1", "2", "3", "4", "5", "6"];
$scope.add = function () {
if ($scope.val === "" || $scope.val === null) {
alert("Please enter value");
}
else if ($scope.values.indexOf($scope.val) != -1) {
alert($scope.val + " value already exists in dropdown, please add new one");
}
else {
$scope.values.push($scope.val);
$scope.val = "";
}
}
});
app.directive('dropDown', function () {
return {
restrict: 'E',
scope: {
object: '='
},
template: '<select style="width:200px;"><option ng-repeat="i in data">{{i}}</option>"',
controller: function ($scope) {
$scope.data = $scope.object;
}
}
});
app.directive('numeric', function () {
return {
restrict: 'C',
link: function (scope, elem, attr) {
elem.bind('keyup', function (e) {
if (/^[0-9]+$/.test(e.currentTarget.value)) {
e.currentTarget.style.backgroundColor = 'green';
} else {
e.currentTarget.style.backgroundColor = 'red';
}
if (e.currentTarget.value === '') {
e.currentTarget.style.backgroundColor = 'white';
}
});
}
}
});
app.directive('alphabet', function () {
return {
restrict: 'A',
link: function (scope, elem, attr) {
elem.bind('keyup', function (e) {
if (/^[a-zA-Z]+$/.test(e.currentTarget.value)) {
e.currentTarget.style.backgroundColor = 'green';
} else {
e.currentTarget.style.backgroundColor = 'red';
}
if (e.currentTarget.value === '') {
e.currentTarget.style.backgroundColor = 'white';
}
});
}
}
});
/* Styles go here */