Wednesday, 17 June 2015

Custom Directives concept

Let me discuss about Custom Directives in Angular JS.

Custom directives are used in Angular JS to extend the functionality of HTML.

They are defined using directive function. A custom directive simply replaces the element for which it is activated. During bootstrap, the Angular JS application finds matching elements and does one time activity using its compile() method of the custom directive. Then it processes the element using link() method of the custom directive based on the scope of the directive. Angular JS provides support to create custom directives for the following elements:

  • Element directive - This activates when a matching element is encountered.
  • Attribute - This activates when a matching attribute is encountered.
  • CSS - This activates when a matching CSS style is encountered.
  • Comment - This activates when a matching comment is encountered.

Let me elaborate further with a suitable example:-


index.html:-
<html>
<head>
<title>Angular JS Custom Directives</title>
</head>
<body>
<h2>AngularJS Custom Directives</h2>
<div ng-app="mainApp" ng-controller="EmployeeController">
<employee name="Mahesh"></employee><br/>
<employee name="Piyush"></employee>
</div>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="directive.js"></script>
<script src="controller.js"></script>
</body>
</html>


app.js:-
var mainApp = angular.module("mainApp", []);


directive.js:-
mainApp.directive('employee', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Employee: <b>{{employee.name}}</b> , ID: <b>{{employee.id}}</b>";
directive.scope = {
employee : "=name"
}

directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
element.html("Employee: <b>"+$scope.employee.name +"</b> , ID: <b>"+$scope.employee.id+"</b><br/>");
element.css("background-color", "lightblue");
}
return linkFunction;
}
return directive;
});


controller.js:-
mainApp.controller('EmployeeController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.name = "Mahesh Parashar";
$scope.Mahesh.id = "E001";
$scope.Piyush = {};
$scope.Piyush.name = "Piyush Parashar";
$scope.Piyush.id = "E002";
});



Screenshots:-





Explanation:-

Here, in the above application, "employee" custom HTML tags are defined. This directive will be activated as soon as any "employee" element is encountered in html "restrict = E", signifies that directive is Element directive.  The template - "directive.template" replaces the complete element with its text. The scope is used to distinguish each employee element based on criteria. The compile - "directive.compile"  is called during application initialization. Angular JS calls it once when html page is loaded. The "linkFunction" used here, is linked with each element with scope to get the element specific data. The controller is defined to update the scope for directive. Here, I use the value of name attribute as scope's child.

Sunday, 14 June 2015

Dependency Injection Concept

Let me show an application on Dependency Injection.

Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component.

 This relieves a component from locating the dependency and makes dependencies configurable. This also helps in making components reusable, maintainable and testable.

Angular JS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.

ü  Value
ü  Factory
ü  Service
ü  Provider
ü  Constant


Value :-
Value is a simple JavaScript object, which is required to pass values to the controller during config phase (config phase is when AngularJS bootstraps itself).


Factory:-
Factory is a function which is used to return value. It creates a value on demand whenever a service or a controller requires it. It generally uses a factory function to calculate and return the value.


Service:-
Service is a singleton JavaScript object containing a set of functions to perform certain tasks. Service is defined using service() function and it is then injected into the controllers.


Provider:-
Provider is used by AngularJS internally to create services, factory etc. during the config phase.
Provider is a special factory method with get() method which can be used to return the value/service/factory.


Constant:-
Constants are used to pass values at the config phase considering the fact that value cannot be used during the config phase.

Let me elaborate the above concepts with a suitable example:-


main.html:-
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<h2>AngularJS Dependency Injection Application</h2>
<div ng-app="mainApp" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script src="angular.min.js">
</script>
<script src="app.js"></script>
<script src="provider.js"></script>
<script src="value.js"></script>
<script src="factory.js"></script>
<script src="service.js"></script>
<script src="controller.js"></script>
</body>
</html>


app.js:-
var mainApp = angular.module("mainApp", []);



controller.js:-
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});



service.js:-
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});


factory.js:-
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});



provider.js:-
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});



value.js:-
mainApp.value("defaultInput", 1);




Screenshots:-







Explanation:-

Here, initially the value is initialized with “1”. Once, I change the value, its corresponding square value will be displayed on the screen.

Friday, 12 June 2015

Services Concept

Let discuss about Angular JS Services in details.

AngularJS supports the concepts of "Seperation of Concerns" using services architecture. Services are javascript functions and are responsible to do a specific tasks only. This makes them an individual entity which is maintainable and testable.

Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.

Each service is responsible for a specific task, i.e.,  $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuild services are always prefixed with $ symbol. There are two ways to create a service:-

  • factory
  • service

Let me elaborate Angular JS Service with a suitable example.


main.html:-
<html>
<head>
<title>Angular JS Services</title>
<script src="angular.min.js"></script>
</head>
<body>
<h2>AngularJS Services Application</h2>
<div ng-app="mainApp" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script src="app.js"></script>
<script src="factory.js"></script>
<script src="service.js"></script>
<script src="controller.js"></script>
</body>
</html>


app.js:-
var mainApp = angular.module("mainApp", []);


controller.js:-
mainApp.controller('CalcController', function($scope, CalcService) {
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});


service.js:-
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});


factory.js:-
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});



Screenshots:-





Explanation:-

Using factory method, I first define a factory and then assign method to it. Using service method, we define a service and then assign method to it. I have also injected an already available service to it.

Saturday, 6 June 2015

Counting any specific item

Now, in this application, you will be able to see the number of names(or items) added in this app.


index.html:-
<html ng-app>
<head> <title> Mean Tutorial </title> </head>
<div ng-controller="meetupsController">
    <h1> There are {{meetups.length}} people added</h1
<ul>
<li ng-repeat="meetup in meetups">
{{meetup.name}}
</li> </ul> <br/>
<form ng-submit="CreateMeetup()">
<input type="text" placeholder="Meetup name" ng-model="meetupName"> </input>
<button type="submit">Add</button>
</form>
</div>
<script src="angular.js"></script>
<script src="meetupsController.js"></script>
</body>
</html>


meetupsController.js:-
function meetupsController($scope)
{
    //$scope.meetupsCount=10;

    $scope.meetups = [
        {name:"Anik"},
        {name:"Rahul"}
    ]

    $scope.CreateMeetup = function()
    {
        $scope.meetups.push({name:$scope.meetupName});
        $scope.meetupName='';
    }
}


Screenshots:-






Explanation:-

Once you will add a name in this app, the number of names added will increase automatically. Here, "length" keyword is used to check the number of names added, so as to increase the number in the webpage.

Use of Push concept

In the previous lesson, I have shown how to add an item and simultaneously how to delete it.

Now, I will show you, only how to add an item in the webpage.


only_add.html:-
<html ng-app="nameApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="angular.min.js"></script>
    <script>
      var nameApp = angular.module('nameApp', []);
      nameApp.controller('NameCtrl', function ($scope){
        $scope.names = ['Ram', 'Raju', 'Shyam'];

        $scope.addName = function() {
          $scope.names.push($scope.enteredName);
          $scope.enteredName='';
        };
      });
    </script>
  </head>
  <body ng-controller="NameCtrl">
    <ul>
      <li ng-repeat="name in names">{{name}}</li>
    </ul>
    <form ng-submit="addName()">
      <input type="text" placeholder="Add Items" ng-model="enteredName">
      <input type="submit" value="add">
    </form>
  </body>
</html>


Screenshots:-






Explanation:-

When we click on the "Add" button, after typing any name in the text box, the name will be displayed on the screen.

Add & Remove Functionality

Now, let me show you how to add any item in Angular JS and by clicking on the remove button, the corresponding item will be erased.


add_delete.html:-
<html ng-app="nameApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="angular.min.js"></script>
    <script>
      var nameApp = angular.module('nameApp', []);
      nameApp.controller('NameCtrl', function ($scope){
        $scope.names = ['Larry', 'Curly', 'Moe'];

        $scope.addName = function() {
          $scope.names.push($scope.enteredName);
          $scope.enteredName = '';
        };

        $scope.removeName = function(name) {
          var i = $scope.names.indexOf(name);
          $scope.names.splice(i, 1);
        };
      });
    </script>
  </head>
  <body ng-controller="NameCtrl">
    <ul>
      <li ng-repeat="name in names">{{name}}
      <a href="" ng-click="removeName(name)">remove</a></li>
    </ul>
    <form ng-submit="addName()">
      <input type="text" ng-model="enteredName">
      <input type="submit" value="add">
    </form>
  </body>
</html>


Screenshots:-






Explanation:-

The names are typed in the text box and then clicked on the "add" button to display it on the screen. When the end-user will click on the "remove" link, the corresponding items will be deleted.

Use of various directives

Today, i will share one application by using few ng directives.

On clicking the "delete" link, the corresponding items will be deleted rather erased from the screen.

sh.html:-
<!doctype html>
<html ng-app="show">
<head>
<meta charset="UTF-8">
  <title>Use Of NG Directives</title>
 <script src="angular.min.js"></script>
</head>

<body>

<div>
    <div ng-controller="FruitCtrl">
      <table>
          <tr ng-repeat="fruit in fruits" ng-mouseenter="hover(fruit)" ng-mouseleave="hover(fruit)" ng-show="fruit.show">
              <td>{{ fruit.id}}&nbsp;&nbsp;</td>
              <td>{{ fruit.name}}&nbsp;&nbsp;</td>
              <td>{{ fruit.price | currency }}&nbsp;&nbsp; </td>
              <td>{{ fruit.count }} &nbsp;&nbsp;</td>
              <td><a href="" ng-show="fruit.showDelete" ng-click="delete(fruit)">Delete</a></td>
          </tr>
      </table>
  </div>
</div>
<script src="sh.js"></script>
</body>
</html>


sh.js:-
var show = angular.module('show', [ ]);
    show.controller("FruitCtrl", function ($scope)
    {

        $scope.fruits = [{
            "id": 1,
            "name": "Apple",
            "price": .50,
            "count": 213,
            "showDelete": false,
            "show": true
        }, {
            "id": 2,
            "name": "Orange",
            "price": .45,
            "count": 665,
            "showDelete": false,
            "show": true
        }, {
            "id": 3,
            "name": "Banana",
            "price": .60,
            "count": 146,
            "showDelete": false,
            "show": true
        }, {
            "id": 4,
            "name": "Kiwi",
            "price": .80,
            "count": 199,
            "showDelete": false,
            "show": true
        }];

        $scope.hover = function(fruit) {
            // Shows/hides the delete button on hover
            return fruit.showDelete = ! fruit.showDelete;
        };

        $scope.delete = function(fruit) {
            // Hides a row of fruit, if the delete button was clicked
            alert("Deleting the " + fruit.name);
            return fruit.show = ! fruit.show;
        };

    });



Screenshots:-







Explanation:-

In the above example, various directives like "ng-show", "ng-repeat", "ng-click", "ng-mouseenter","ng-mouseleave" has been used.

Monday, 1 June 2015

Use of ng-include & ng-show

Today, I will share one application where I have used ng-include and ng-show directives of Angular JS.


includes.html:-
<html>
<head>
<title>Angular JS Includes</title>
<script src="angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="studentController">
<form>
            <b>Select The Radio Button</b>
            <label class="radio-inline" for="first">
                <input id="first" type="radio" name="regtype" ng-model="regtype" value="basic">Basic Details
            </label>
            <label class="radio-inline" for="other">
                <input id="other" type="radio" name="regtype" ng-model="regtype" value="subject">Subject Details
            </label>
        </form>
<div ng-show="regtype == 'basic'" ng-include="'main.html'"></div>
<div ng-show="regtype == 'subject'" ng-include="'subjects.html'"></div>
</div>
<script src="app.js"></script>
<script src="controller.js"></script>
</body>
</html>


main.html:-
<table border="0">
<tr><td>Enter first name:</td><td><input type="text" ng-model="student.firstName"></td></tr>
<tr><td>Enter last name: </td><td><input type="text" ng-model="student.lastName"></td></tr>
<tr><td>Name: </td><td>{{student.fullName()}}</td></tr>
<tr><td>Fees: </td><td>{{student.fees}}</td></tr>
</table>


subjects.html:
<p>Subjects:</p>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat="subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>


app.js:-
var mainApp = angular.module("mainApp", []);


controller.js:-
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Anik",
lastName: "Acharjee",
fees:1500,
subjects:[
{name:'Physics',marks:75},
{name:'Chemistry',marks:70},
{name:'Math',marks:74},
{name:'English',marks:79},
{name:'Computer Science',marks:73}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});



Screenshots:-








Explanation:-

In the above application, two radio buttons are developed. When I click on, one of the radio button, it will display one page and when I click on other radio button, it will display another page.

Since, in the code, I have added ng-show & ng-include,it will display as per the radio click.

In every radio button, one value is assigned. When that value is triggered, by clicking on the radio button, the webpage which has been included to it, using "ng-include", will be shown on the page.