X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Saturday, March 25, 2017

Advance directives in Angularjs

Introduction
AngularJS directives are one of the powerful components in AngularJS framework.Directives in AngularJS help us to extend the basic HTML elements and let us reuse the directives in other pages and test it.

Directives in detail with examples
Here we will discuss the directives which are used mostly in our AngularJS application with an example –

ng-repeat

This directive is used to instantiate each item from the collection. One more thing to note here is that, each item will get its own scope and using – “$index” we can get the index of an item in the collection.

Below are some of the properties can be used along with ng-repeat –

  • $index – This will be the index of the item in the item collection.
  • $first – This property is used to return the first item from the item collection.This property returns the Boolean. So ideally we can use this in the ng-if directive.
  • $last – This property is used to return the last item from the item collection. This property returns the Boolean. So ideally we can use this in the ng-if directive.
  • $even - This property is used to return the even value of the $index.This property returns the Boolean. So ideally we can use this in the ng-if directive.
  • $odd - This property is used to return the odd value of the $index.This property returns the Boolean. So ideally we can use this in the ng-if directive.

Example -
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="myNgRepeatApp" ng-controller="myNgRepeatCtrl">

<div ng-repeat="name in names">
   <div ng-class='nameClass(name, $index)' > {{name}}</div>  
</div>

<br/>
<br/>
//$first is used to get the first name from the list.
//instead we can use - ng-if="$index > 0".
<div ng-repeat="name in names" ng-if="$first"> 
   <div ng-class='nameClass(name, $index)' > {{name}}</div>  
</div>

<br/>
<br/>

//$last is used to get the last name from the list.
//instead we can use - ng-if="$index >names.length - 2".
<div ng-repeat="name in names" ng-if="$last">
   <div ng-class='nameClass(name, $index)' > {{name}}</div>  
</div>

<script>
var app = angular.module("myNgRepeatApp", []);
app.controller("myNgRepeatCtrl", function($scope) {
  $scope.names = [
    "John Martin",
    "Jack Klop",
    "Theo Matty",
    "Eart Young",
  ]
 
  $scope.nameClass = function(item, index){
		 if(index == 0){
		     return item;
         }
        return '';
    };  
});
</script>

</body>
</html>

ng-switch

This directive is used to hide and show the HTML element depending on the expression.

Parent element will have directive called – “ng-switch” and the child elements will have – “ng-switch-when”. If the expression is matched, then the HTML element will be displayed. We can define the default element also using directive called – “ng-switch-default”.

Syntax -
<element ng-switch="myExpression">
  <element ng-switch-when="myvalue"></element>
  <element ng-switch-when="myvalue"></element>
  <element ng-switch-default></element>
</element>

Example -
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">

List of languages are :
<select ng-model="varLang">
  <option value="eng"> English </option>
  <option value="esp"> Spanish </option>
  <option value="hn"> Hindi </option>
  <option value="por"> Portugese </option>
  <option value="itl"> Italian </option>
</select>

<hr>
<div ng-switch="varLang">
  <div ng-switch-when="eng">
     <h1> English is my language </h1>
     <p> This is my test content in english. </p>
  </div>
  <div ng-switch-when="esp">
     <h1> Spanish is my language </h1>
     <p> Este es el contenido de mi ensayo en Inglés. </p>
  </div>
  <div ng-switch-when="hn">
     <h1> Hindi is my language </h1>
     <p> यह अंग्रेजी में मेरी परीक्षा सामग्री है. </p>
  </div>
  <div ng-switch-when="por">
     <h1> Portugese is my language </h1>
     <p> Este é o meu conteúdo do teste em Inglês. </p>
  </div>
   <div ng-switch-when="itl">
     <h1> Italian is my language </h1>
     <p> Questo è il mio test del contenuto in inglese. </p>
  </div>
  <div ng-switch-default>
     <h1>Switch</h1>
     <p>Select my language from the dropdown.</p>
  </div>
</div>
</body>
</html>

ng-include

This directive is used to include the external HTML file in our AngularJS application. By default, the given template URL will be restricted to fetch from the same domain. But ng-include directive will load the HTML file from other domains as well.

Below are some of the syntaxes to use ng-include in AngularJS application –

Syntax -
<element ng-include="my filename" onload="my expression" autoscroll="my expression" >
</element>
<ng-include src=" my filename" onload=" my expression" autoscroll=" my expression" >
</ng-include>
Here my file name will return the file name, “onload” is optional and it will have an expression, which evaluates whether the included file is to be loaded.
“Autoscroll” is also an optional parameter and it evaluates the expression, whether there should be an option to scroll.

Example -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module("myNgIncludeApp", []);
app.controller("myNgIncludeCtrl", function($scope) {
   $scope.countries =
      [{ name: 'USA', url: 'USA.html'},
       { name: 'UK', url: 'UK.html'}];
    $scope.country = $scope.countries[0];
});

</script>
</head>

<body ng-app="myNgIncludeApp">
  <div ng-controller="myNgIncludeCtrl">

	  <select ng-model="country" ng-options="c.name for c in countries">
	   <option value="">(blank)</option>
	  </select>
	  url of the countryName: <code>{{country.name}}</code>
	  <hr/>
	  <div class="slide-animate-container">
		<div class="slide-animate" ng-include="country.url"></div>
	  </div>
  
  </div>
  
</body>
</html>
Create USA.html & UK.html and add some contents to load the page.


Dynamically adding elements to the page


In some cases, we need to add the elements to the page on user actions.

Let us create an example to add a new element to a page -

Example -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script>
var app = angular.module('dynamicElementApp', []);

app.controller('dynamicElementCtrl', function($scope) {

  $scope.myItems = [];

  $scope.newitemsToAdd = [{
    firstName: '',
    lastName: ''
  }];

//Method to add an item.
  $scope.add = function(newitemToAdd) {

    var index = $scope.newitemsToAdd.indexOf(newitemToAdd);

    $scope.newitemsToAdd.splice(index, 1);

    $scope.myItems.push(angular.copy(newitemToAdd))
  }

//Method to add a new item to a page.
  $scope.addNew = function() {
    $scope.newitemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});

</script>
</head>

<body ng-app="dynamicElementApp" ng-controller="dynamicElementCtrl">
  
  <div ng-repeat="myItem in myItems">
    {{myItem.firstName}} {{myItem.lastName}}
  </div>
//Displaying the already added items.
  <div ng-repeat="newitemToAdd in newitemsToAdd">
    <input type="text" ng-model="newitemToAdd.firstName" />
    <input type="text" ng-model="newitemToAdd.lastName" />
    <button ng-click="add(newitemToAdd)">Add</button>
  </div>
  <div>
    <button ng-click="addNew()">Add new</button>
  </div>
</body>
</html>

Hope this article will help you. Please comment your thoughts below.





Friday, October 9, 2015

AngularJS Grid Example


Introduction

In this article i will try to show the sample grid in AngularJS and adding the button in each row to get the selected row details. I will use the same sample Web API service created in my previous article.


Practical Approach

Below is the screenshot of the sample project created -



Now lets move on to each file in the project -

<!doctype html>
<html>

<head>
<title> Grid Example </title>

</head>

<body ng-app="myApp">
   <div class="page-content">
   <div class="row">
    <div class="col-md-2">
    <div class="sidebar content-box" style="display: block;">
     <ul class="nav">
      <!-- Main menu -->
       <li>
         <a href="#/GridExample" <i class="glyphicon glyphicon-home"></i> Grid Example</a>
       </li>
      </ul>
    </div>
     </div>
     
   <div class="col-md-10">
      <div class="content-box-header panel-heading">
     <div class="panel-title">Sample Grid Example</div>
      </div>

    <div class="row">
     <div class="col-md-12 panel-info">
      <div class="content-box-large box-with-header">
       <div ng-view></div>
      </div>

     </div>
    </div>

   </div>
  </div>
 </div>

<!-- Libaries for Bootstrap for controls -->
<!--Starts Here-->
<link href="scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="scripts/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/bootstrap/js/bootstrap.min.js"></script>
<!--Ends Here-->

<script type="text/javascript" src="scripts/angular.min.js"></script>
<script type="text/javascript" src="scripts/angular-route.js"></script>

<link href="css/styles.css" rel="stylesheet" />
<link href="content/ui-grid/ui-grid-unstable.css" rel="stylesheet" />
<link href="content/css/custom.css" rel="stylesheet" />

<script type="text/javascript" src="scripts/ui-grid-unstable.js"></script>

<script src="app.js"></script>
<script src="config.js"></script>

<script src="services/sampleService.js"></script>
<script src="controllers/sampleController.js"></script>

</body>
</html>

Above "index.html" has the references for controllers, services and stylesheet files. Library - "ui-grid-unstable.js" is used for loading the grid and it has functions required by the grid and stylesheet file also highlighted above.

If you checked my article it has all these files created already but in this example i will modify the controller part but service will be untouched.

So controller code for loading the grid -

myApp.controller('sampleCtrl', ['$scope', '$http', 'sampleService', function ($scope, $http, sampleService) {
 var products = sampleService.getProducts();

 products.then(function (response) {
  $scope.gridOptions = {
   data: response.data
  };
 });

 $scope.getProdName = function (row) {
  alert(row.entity.ProductName);
 };

 $scope.gridOptions = {
  enableFiltering: false,
  enablePaging: true,
  onRegisterApi: function (gridApi) {
   $scope.gridApi = gridApi;
  },
  columnDefs: [
    { name: 'Product Id', field: 'ProductId', width: 150 },
    { name: 'Product Name', field: 'ProductName' },
    {
     name: 'Details',
     cellTemplate: '<button class="btn btn-info btn-xs" 
                          ng-click="grid.appScope.getProdName(row)">View Product Name</button>',
                 enableFiltering: false,
                 enableSorting: false
       }
   ]
};

}]);


As shown above button control is added in "cellTemplate" section and on click of the button, product name value of the respective row will be popped up using function - "getProdName()".

For grid to work we should add the dependency while registering a module -

var myApp = angular.module('myApp', ['ngRoute', 'ui.grid']);

Below is the screenshot of the working example -



Hope this helps.




Thursday, October 8, 2015

Spinner Control For AngularJS


Introduction

In this article lets add a spinner control to show the loading of data in our AngularJS application.
I will use the same sample Web API service created in my previous article.


Practical Approach

As i said i am going to use the same Web API service and below is the project structure of AngularJS application -



Nothing fancy. It has the basic structure of AngularJS application. Now lets go through each file here in the solution -

I have a root file - "Index.html" which is my parent page and


<!doctype html>
<html>

<head>
 <title> Spinner Example </title>

</head>

<body ng-app="myApp">
 <div class="page-content">
  <div class="row">
   <div class="col-md-2">
    <div class="sidebar content-box" style="display: block;">
     <ul class="nav">
      <!-- Main menu -->
      <li><a href="#/SpinnerExample"<i class="glyphicon glyphicon-home"></i> Spinner Example</a></li>
     </ul>
    </div>
   </div>
   <div class="col-md-10">
    <div class="content-box-header panel-heading">
     <div class="panel-title">Sample Spinner Example</div>
    </div>

    <div class="row">
     <div class="col-md-12 panel-info">
      <div class="content-box-large box-with-header">
       <div ng-view></div>
      </div>

     </div>
    </div>

   </div>
  </div>
 </div>

 <span us-spinner="{radius:30, width:8, length: 16}"></span>

 <!-- Libaries for Bootstrap for controls -->
 <!--Starts Here-->
 <link href="scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
 <link href="scripts/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" />
 <script type="text/javascript" src="scripts/bootstrap/js/bootstrap.min.js"></script>
 <!--Ends Here-->

 <script type="text/javascript" src="scripts/angular.min.js"></script>
 <script type="text/javascript" src="scripts/angular-route.js"></script>

 <link href="css/styles.css" rel="stylesheet" />
        <!-- Libaries for Spinner--> 
        <!--Starts Here-->
        <script type="text/javascript" src="scripts/spinner/spin.min.js"></script>
 <script type="text/javascript" src="scripts/spinner/angular-spinner.min.js"></script>
 <script type="text/javascript" src="scripts/spinner/angular-loading-spinner.js"></script>
        <!--Ends Here-->
        <script src="app.js"></script>
 <script src="config.js"></script>

 <script src="services/sampleService.js"></script>
 <script src="controllers/sampleController.js"></script>

</body>
</html>

This file has all relevant file paths like - controllers, scripts and services, which are required for this demo and observe the line required for spinner control is highlighted along with spinner scripts.

For demonstration purpose i have created a service - "sampleService.js", which will call the Web API
service to get the data.

myApp.service('sampleService', function ($http) {
 this.getProducts = function () {
  return $http.get('http://localhost:53308/api/Product/');
 }
});

And controller which uses the above service -

myApp.controller('sampleCtrl', ['$scope', '$http', 'sampleService', function ($scope, $http, sampleService) {
 var products = sampleService.getProducts();

 products.then(function (response) {
  //once the process data
 });

}]);

As can be seen in the above code, when the data process is completed spinner is hidden and if there is a pending http request then the spinner is shown as per the below line of code in "index.html" -

<span us-spinner="{radius:30, width:8, length: 16}"></span>

Below is the directive is used for spinner -

(function () {
 angular.module('ngLoadingSpinner', ['angularSpinner'])
    .directive('usSpinner', ['$http', '$rootScope', function ($http, $rootScope) {
     return {
      link: function (scope, elm, attrs) {
       debugger;
       $rootScope.spinnerActive = false;
       scope.isLoading = function () {
        return $http.pendingRequests.length > 0;
       };

       scope.$watch(scope.isLoading, function (loading) {
        $rootScope.spinnerActive = loading;
        if (loading) {
         elm.removeClass('ng-hide');
        } else {
         elm.addClass('ng-hide');
        }
       });
      }
     };

    }]);
}).call(this);

Below is the screenshot of the spinner in the page -



and Plunker working demo - http://plnkr.co/edit/2bkqH67BURHqPHvXFpQT?p=preview

Hope this helps.




Tuesday, October 6, 2015

Form validation in Angularjs Part - 1

Introduction

This article focuses on adding the validation on form elements. This article will cover the basic validations in AngularJS and in coming posts i will try to cover the custom validation and dynamic validations.

Approach

Lets discuss some basic form validations in AngularJS -

Below is the Angular application structure -




Here one controller - "validationController.js" is added just one HTML page - "index.html" is added for adding the form controls.


Below is the content of "index.html" -

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Validations</title>

<link href="css/bootstrap.min.css" rel="stylesheet" />
</head>
<body ng-controller="validationCtrl">

<script src="scripts/angular.min.js"></script>

<script src="app.js"></script>
<script src="controllers/validationController.js"></script>

<form name="validationForm" novalidate class="form-horizontal" ng-submit="validationViewModel.submit()">

<!-- Text Validation-->
<div class="form-group">
 <label class="col-lg-2 control-label">Name</label>
     <div class="col-sm-2">
         <input type="text" class="form-control" ng-model="validationViewModel.Name" placeholder="Enter Name" name="Name" 
              required 
              ng-maxlength="10" 
              ng-minlength="5" /> 
     </div>

     <div class="help-block" style="color:red" ng-messages="Name.$error" 
                  ng-show="validationForm.Name.$dirty && validationForm.Name.$invalid">
           <span ng-show="validationForm.Name.$error.required">Enter Name.</span>
           <span ng-show="validationForm.Name.$error.maxlength">Maximum limit reached.</span>
    <span ng-show="validationForm.Name.$error.minlength">Enter Minimum length.</span>
     </div>
</div>


<!-- Email Validation-->
<div class="form-group">
  <label class="col-lg-2 control-label">Email</label>
      <div class="col-sm-2">
           <input type="email" class="form-control" ng-model="validationViewModel.Email" placeholder="Enter Email" name="Email" 
                 required />
      </div>
   
     <div class="help-block" style="color:red" ng-messages="Email.$error" 
                ng-show="validationForm.Email.$dirty && validationForm.Email.$invalid">
          <span ng-show="validationForm.Email.$error.required">Enter Email.</span>
          <span ng-show="validationForm.Email.$error.email">Enter Valid Email.</span>
     </div>
</div>

<!-- RadioButton Validation-->
<div class="form-group">
  <label class="col-lg-2 control-label">Gender</label>
      <div class="col-sm-2">
           <input type="radio" class="form-control" ng-model="validationViewModel.Gender" placeholder="Select Gender" value="male" 
               name="Gender" 
               required />
           <input type="radio" class="form-control" ng-model="validationViewModel.Gender" placeholder="Select Gender" value="female" 
               name="Gender" 
               required />
       </div>
    
     <div class="help-block" style="color:red" ng-messages="Gender.$error" 
               ng-show="validationForm.Gender.$dirty && validationForm.Gender.$invalid">
           <span ng-show="validationForm.Gender.$error.required">Select Gender.</span>
     </div>
</div>

<div class="form-group">
  <div class="col-lg-offset-2 col-sm-8">
       <button type="submit" class="btn btn-primary" ng-click="submitted=true">Save</button>
   </div>
</div>

</form>

</body>
</html>
);

As shown above there are 3 types of validations - "Text, "Email" and "Radio button" validations.

Validations will  be done whenever the controls are changed ($dirty) and the value is invalid. ($invalid).

So suppose if you want the validations to be fired irrespective of "$dirty" flag or on the click "Save" button then we can add some tweak to the existing HTML like below -

<div class="form-group">
  <div class="col-lg-offset-2 col-sm-8">
       <button type="submit" class="btn btn-primary" ng-click="submitted=true">Save</button>
   </div>
</div>


To the existing button control add the ng-click event to make the "submitted" to true. And existing validations can be modified like below -

ng-show="submitted || (validationForm.Email.$dirty && validationForm.Email.$invalid)"> 

So do the above changes in all the places wherever it is required. This line code to check whether directly "Save" button is clicked or else follow the same validations rules.

After adding this line of code this is how our page shows -



Plunkr Demo - http://plnkr.co/edit/GHZ4sflo7IV7ynLf1wNS?p=preview

Hope this helps.




Thursday, September 10, 2015

AngularJS Routing Simple Example


Introduction to AngularJS Routing

AngularJS allows us to divide the page into multiple sections or views. So for redirecting between the views we use AngularJS Routing. These views can be bind to different controllers or same controller.

AngularJS Routing Patterns

Below are the sample route patterns in AngularJS if you are running the application in local machine -

http://localhost/index.html#electronics
http://localhost/index.html#furniture
http://localhost/index.html#books

As you can see all the urls have "#" sign, which is used to denote the view name. So our parent view name here is - "Index.html" and child view names are - "electronics", "furniture" and "books".

AngularJS Routing Library

Now lets create a sample e commerce AngularJS application for AngularJS Routing demo -
First lets create a module for our AngularJS application -

var myApp = angular.module('myApp', ['ngRoute']);

For routing to work we need to have module - 'ngRoute' so its added as dependency module above.
"$routeProvider" is also used for configuring the routes in AngularJS.

So for these routing configurations include library - "angular-route.js" -

<script src="scripts/angularJS/angular.min.js" type="text/javascript"></script>
<script src="scripts/angularJS/angular-route.js" type="text/javascript"></script>

AngularJS Routing Code

Below is the sample code for routing -

myApp.config(function ($routeProvider) {
 $routeProvider
    .when('/Electronics',
         {
          templateUrl: 'views/electronics.html',
          controller: 'catgrController'
         })
    .when('/Men',
        {
         templateUrl: 'views/men.html',
         controller: 'catgrController'
        })
    .when('/Women',
    {
     templateUrl: 'views/women.html',
     controller: 'catgrController'
    })
     .when('/Furniture',
    {
     templateUrl: 'views/furniture.html',
     controller: 'catgrController'
    })
  .when('/Books',
    {
     templateUrl: 'views/books.html',
     controller: 'catgrController'
    })
  .otherwise('/',
  {
   templateUrl: 'Index.html',
   controller: 'catgrController'
  });
});

The above code looks straightforward. Based on the url view has been displayed. Below is my HTML for routing -

<div class="page-content" ng-controller="hmcontroller">
<div class="row">
  <div class="col-md-2">
    <div class="sidebar content-box" style="display: block;">
        <ul class="nav">
          <!-- Main menu -->
          <li><a href="#/Electronics" ng-click="getSelectedText('Electronics')"><i class="glyphicon glyphicon-home"></i> Electronics</a></li>
          <li><a href="#/Men" ng-click="getSelectedText('Men')"><i class="glyphicon glyphicon-edit"></i> Men</a></li>
          <li><a href="#/Women" ng-click="getSelectedText('Women')"><i class="glyphicon glyphicon-list"></i> Women</a></li>
          <li><a href="#/Furniture" ng-click="getSelectedText('Furniture')"><i class="glyphicon glyphicon-list"></i>Furniture</a></li>
          <li><a href="#/Books" ng-click="getSelectedText('Books')"><i class="glyphicon glyphicon-list"></i> Books</a></li>
        </ul>
    </div>
  </div>
  <div class="col-md-10">
    <div class="content-box-header panel-heading">
        <div class="panel-title">{{pageTitle}}</div>
    </div>
  <div class="row">
  <div class="col-md-12 panel-info">
      <div class="content-box-large box-with-header">
        <div ng-view></div>
      </div>
   </div>
 </div>
</div>
</div>
</div>

As you can see in the above code snippet menu options are in "<li>" tag. "hmcontroller" is my controller script, which is used for displaying the page name clicked.

hmcontroller.js -

myApp.controller('hmcontroller', ['$scope', function ($scope) {

 $scope.getSelectedText = function (selectedText) {
  $scope.pageTitle = selectedText;
 };

}]);

Below is the output -


Hope this post is useful. Please put your thoughts in the comment section below.





Saturday, September 5, 2015

Angularjs interview questions for Freshers and Experienced

Below are the list of Angularjs interview questions for Freshers and Experienced  -


1) What are modules in AngularJS?

2)  How AngularJS application works?

3) What is the use of "$scope" in AngularJS?

4) How the Routing works in AngularJS?

5) What is the need of "service" in AngularJS?

6) How we can declare constant variables in AngularJS?

7) How we can "$http" methods in AngularJS?

8) Explain Dependency Injection in AngularJS?

9) List all the directives in AngularJS?

10) What are filters in AngularJS?

11) How the validation works in AngularJS?

12) Explain AngularJS booting process?

13) Why to use "ng-disable" directive in AngularJS?

14) How to implement a custom directive in AngularJS?

15) What is the use of "Controller as" syntax in AngularJS?