AngularJS Directive, Modules and Controller


What is AngularJS directive?

These are the most important component of AngularJS directive, They are used to extend the html elements and AngularJS has lots of inbuilt directive and we can also create our own directive if we want.

Angular Inbuilt Directive

The Angular inbuilt Directives starts with the "ng" keyword like ng-modal, ng-bind, ng-click, ng-if etc. If you start directive with ng, your html page shows that this is invalid attribute but it works fine. if you make your html page valid then simply write data-ng-bind means "data" keyword before the ng directive.

See Example..


Angular-Inbuilt-Directive Example
<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Welcome in the Angular JS</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.1/angular.min.js"></script>
</head>
<body ng-app>
    <div>
        Enter your name <input type="text" data-ng-init="name='Default Name'" data-ng-model="name">
        Your name is <span data-ng-bind="name"></span>
    </div>
</body>
</html>

Output


AngularJs Modules

Modules are used to divide an angular app into small, reusable and functional components which can be integrated with other angular app. In this, Each module is identified by a unique name and can be dependent on other modules. In AngularJS, every web page or view can have a single module assigned to it via ng-app directive.

In the below example, ng-app="sampleApplication" is defining the module as "sampleApplication".

Angular JS Application

To work with Angular JS Application you first need to define the Angular JS Application. Angular JS Modules defines the Angular Application and Angular JS Controller controls the Application. Lets see the example to understand this properly..


Angularjs-Application-Start Example
<!DOCTYPE html>
<html lang="en-US">
<head>
 <title>Welcome in the Angular JS</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.1/angular.min.js"></script>
</head>
<body ng-app="sampleApplication">
  <div ng-controller="sampleController" >
     Enter your name <input type="text" ng-model="name">
  </div>
<script> 
  var app = angular.module("sampleApplication", []); 
  app.controller("sampleController", function($scope) { 
    $scope.name="Clark" 
  }); 
</script>    
</body>
</html>

Output


"angular.module" define the Angular JS Application with the name of "sampleApplication".The second parameter [ ] is for dependency purpose where you can define the dependencies for your application.Later you can see the example for the dependency.Further "app.controller" define Controller with the name "sampleController". Now to define Angular JS Application in html page we have directive "ng-app"."ng-controller" directive tells that this controller ( sampleController ) controls this Div element.