Simple Angular js directives
Introduction
Directies are markers on a DOM element, such as an attribute, or element name, that attaches behaviors to the DOM element. Several build-in directives in Angular js are ngBind, ngDisable, ngClick, ngShow, and ngModel.
Demonstration
ng-bind
ngBind may bind the content of a HTML element with value of a given expression and update the value as the value of the expression changes. Here, I bind the name and nickname in the following sentence with the input text field.
Name:
Nickname:
My name is and my nickname is
ng-disable
ngDisabled sets the disabled attribute on the element as the expression inside ngDisabled is true. Here, I bind the expression Switch on the toggle checkbox. The button would be disabled as the checkbox is checked.
Toggle
ng-click
ngClick would evaluate the expression upon tap. This directive would be deprecated beginning with Angular 1.5. Click on the button and there's a scope variable incrementation.
form validation
Inputs of type email must have a value in the form of username@domainname. If the email is blank, a message of required email would be shown. If the format of the email isn't username@domainname, a message of invalid email would be shown.
Angular js setup
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.email = '';
});
</script>
Controller code
<div ng-app="myApp" ng-init="name='name';nickname='nickname';Switch=true;count=0">
</div>
ngBind
<p>Name: <input type="text" ng-model="name"></p>
<p>Nickname: <input type="text" ng-model="nickname"></p>
<p>My name is <span ng-bind="name"></span> and my nickname is <span ng-bind="nickname"></span></p>
bgDisabled
Bind the checkbox with Switch using ngModel. And assign Switch as the expression in ngDisabled.<p>
<button ng-disabled="Switch">Toggle button</button>
</p>
<p>
<input type="checkbox" ng-model="Switch">Toggle
</p>
ngClick
<div>
<button ng-click="count = count + 1">Click me!</button>
<p><span ng-bind="count"></span></p>
</div>
form validation
<form name="myForm" ng-controller="validateCtrl" novalidate>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit" ng-disabled="myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>