Front End Developer

Directives in Angularjs

Directives are markers on a DOM element which tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element. In general most of everything is a directive in AngularJS.
AngularJS directive can be used as:-
 Element name
 Attribute
 Class
 Comment
-Life cycle of directive begins and end only under the process of bootstrapping i.e. before the page is rendered.
-Below are the four functions which executes during the life cycle of directive if those are there in directive.
a) compile :- allows the directive to manipulate DOM before it is complied and linked, during this phase it modify the DOM and directives i.e. by adding removing and changing.
b)Controller :- controller provides the communication. Sibling and child controller can request for information to their siblings and parent’s controller.
c) pre-link :- Within this function manipulation with $scope is done(if any) so that the manipulated scope can be used in post-link function.
d) post-link : – This is the method which performs most of the work of the directive.
So if all four functions are used then structure will be something like below:-

.directive("mydirective",function () {
return {
controller: function() {
//code for controller.
},
compile:{
// compile related code.
return {
pre: function() {
// code for pre-link.
},
post: function() {
// code for post-link.
}
};
}
}
})

Signature for both i.e. pre and post link are same, the main difference is in the order those are executed. In general you will be not seeing more usage of pre-link function. Mostly controller and post-link are enough for handing basic purpose of a directive. In those case ‘link’ will be simply referring to the ‘post-link’.

.directive("mydirective",function () {
return {
controller: function() {
//code for controller.
},
link: function() {
// code for post-link.
}
}
})

Below is the sample code for creating a custom directive. In this directive things are very simple and only link method is being used. The thing to notice here is that we are not using the ‘$scope’ inside the link function, instead we are using scope which is called ‘isolated scope’.

index.html:-

<html>
   <body>
<div ng-app="mainApp">
	     Enter Percentage :- <input ng-model="percentage"></input>

	    <percentage-dir value="percentage" ng-init="percentage = 15"></percentage-dir></div>
<script src ="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

    <script>
        var mainApp = angular.module('mainApp', []);
        
		  mainApp.directive("percentageDir", function (){
		    return {
		        restrict: 'E',
		        scope: {
		            value: '=',
		        },
		        templateUrl: 'directivetemplates/percentageTemplate.html',
		        link: function(scope, element, attrs) {
		           element.on('click', function () {
	                  alert('You cannot write Here.');
	               
	              });
		           scope.canvas = element.find('canvas')[0];
		           scope.context = scope.canvas.getContext('2d');
		 
		           scope.$watch('value', function(currentValue) {
		             fillWidth = Math.ceil(currentValue / 100 * scope.canvas.width);
		             scope.context.fillStyle = "#cccccc";
		             scope.context.fillRect(0, 0, scope.canvas.width, scope.canvas.height);
		             scope.context.fillStyle = "#0000FF";
		             scope.context.fillRect(0, 0, fillWidth, scope.canvas.height);
		           });
		        }        
		    };
		});
      </script>
</body>
</html>

directivetemplates/percentageTemplate.html:-

<canvas width='200' height='30' style="border-style: solid;border-width: 2px">
</canvas>

Hope this will be helpfull to someone.

Class in ECMAScript 6.0

As JavaScript is a prototype based object oriented language so we were require to do simulation for creating class in javascript. But ECMAScript 6 defines classes in actual by introducing the ‘class’ keyword.Before ECMAScript 6.0 how to create a class in javascript we have seen in:-
https://smartfrontend.wordpress.com/2016/05/29/creating-class-in-javascript/

But with ECMAScript 6.0 there is clean way for defining the class in javascript.Writting same class as in above mentioned link in ECMAScript 6.0.Below is code for creating class with name ‘Company’:-


class Company {
	//Define Constructor of Class.
    constructor(name,yearOfFoundation,noOfEmployee){
        this.name = name;
        this.yearOfFoundation = yearOfFoundation;
        this.noOfEmployee = noOfEmployee;
    }

    getCompanyInfo() {
        return this.name + ' ' + this.yearOfFoundation + ' '+ this.noOfEmployee;
    }
}

We can create the object of this class as :-


  //Creating Instance of Company.
  var company = new Company('Comp1','1997','1000');

  //calling method of instance.
  var str = company.getCompanyInfo();

Hope this will be helpful for someone.

“No ‘Access-Control-Allow-Origin’ header is present on the requested resource”

You may get this kind of message when you will be trying to access any rest web service from external server.Your message should be something like:-

XMLHttpRequest cannot load http://Your Service url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://Your Service requesting url’ is therefore not allowed access.

The reason for this is that a XMLHttpRequest is being made to a different domain from the domain in which your page is available.Though you will be able to access this service using the postman.This security mechanism is known as ‘Cross-Origin Resource Sharing‘(CORS).

You can read about this in detail from:-
https://www.w3.org/TR/cors/

So for out-coming from this issue we will require to add CORS support on our server i.e. on the server where our web-service is residing.According to your server you can configure your server as per below link:-

http://enable-cors.org/server.html

After making changes as per above link you should now be able to access the web-service from the mentioned server.

Hope this will helpful for someone.

AngularJS Development with Grunt, Bower and Yeoman

In this sample application tutorial we will be using multiple tools for different purpose for an AngularJS application development. Let’s just know about their names and purpose.

Karma:-Karma is a test runner tool for JavaScript which runs on Node JS.

Jasmine:-Behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript framework.

Grunt:-Grunt is JavaScript Task Runner.

Bower:-Bower is a package manager for web which manages multiple components like html, JavaScript, css, images etc.

Yeoman:-Yeoman is an open source client-side development stack, consisting of tools and frameworks intended to help developers quickly build high quality web applications. This contains Grunt, Bower, and the scaffolding tool Yo. Yo generates boilerplate code with the help of generators.

I am using Aptana Studio (http://www.aptana.com/) as my IDE for this sample tutorial. And have also tested this sample with Eclipse IDE. Now let’s move step by step towards creating our sample application using above tools.

Step 1:– First of all install below three tools which are backbone for your further tools.
a)GIT (https://git-scm.com/)
b)NodeJs (https://nodejs.org/en/download/)
b)NPM :-Once you have installed npm you can update it using:-
npm install npm –g
and you can check the version of it using :-
npm –v

Now here is one important point to note.As I am using Aptana Studio as IDE so I am just creating the new Project of Default type with name ‘YourApplicationName’ so that my terminal will be open for this project only. Then I will open my terminal so that all structure will apply to this application only.

Step 2:-
a) Install yeoman, grunt and bower all together by using yo.
npm install -g yo grunt-cli bower

b) Install Angular generator.
npm install -g generator-angular

Step 3:-For Scaffolding Angular App run command below.
a) yo angular

Now you will be asked for multiple yes and no options.Include whatever you want to add and want to leave in your application.E.g. I am just selecting bootstrap and angular-route.js.

Now after finishing the processing of Step 3 you will able to see you application folder full of the multiple files and folders.You will able to see ‘app’ directory there which contains html, css and JavaScript and inside this only we will be doing our development.

Now below is Step 4 for installing Testing Tools. We will be talk on using these later on someday. So you Can avoid this step for right now and Directly jump to Step 5.

Step 4:-
a)npm install karma-jasmine –save-dev
b)npm install karma-chrome-launcher –save-dev

Step 5:- Running the application.Just type below command:-
grunt serve

Application will run in ur browser.I will be update this post soon for the Step 4.

 

 

Hope this post will helpful to someone.

Posting JSON data to Server Using RESTful service in AngularJS

This is related to just demonstrating posting of data to server in a simple case.If we are not using ‘factory’in our application then we can post data to server by simply putting code inside the controller.
Inside your controller create a method namely submitToServer or what ever you want to name it,like below:-

$scope.submitToServer = function(){
	$http({
	url: urlOfService,
	method: 'POST',
	data: {
			id : $scope.emp.name,
			name: $scope.emp.name,
			age: $scope.emp.age,
			phoneNumber: $scope.emp.phoneNumber,
			street: $scope.emp.street,
			city: $scope.emp.city,
			state: $scope.emp.state
		  },
	headers: { 'Content-Type': 'application/json;charset=utf-8' },
	dataType : "JSONP",
	//timeout: 1,
	//cache: false,
	//transformRequest: false,
	//transformResponse: false
	}).then(function (results) {
		alert("Data Posted Successfully.");
		$scope.getDataFromServer();
	}).catch(function (e) {
			alert(e +" Exception In Posting Data");
			});
	}
  };
}

Now inside your module you can call this method as below in click of any button:-

<button ng-click="submitToServer()">Submit To Server</button>

Please note that all data which we are sending is inside ‘data’ node only.

Hope This will Help Someone.

Executing function inside Controller On Document/Module Ready In AngularJS

Some times there are scenarios when you want to Run any function inside the controller without any user interaction.
For handling of this case we use :-
angular.element(document).ready() method for attaching callback method.And on that callback we can call which ever method we want to execute.

.controller('YourController',
['$scope',
function ($scope) {

$scope.yourMethod = function(){
//Give definition to your function.
alert("Inside yourMethod");
}

angular.element(document).ready(function () {
$scope.yourMethod();
});

}]);

One more thing to note that as we are dealing with modules so in some cases it is possible that instead of document we want to call this method on load of module.
For such case you can replace :-

angular.element(document).ready(function () {
$scope.yourMethod();
});

By below code,which is just related to that particular modules.

$scope.$on('$viewContentLoaded', function ($evt, data) {
$scope.yourMethod();
});

Hope This will Help Someone.

Asynchronous Module Definition( i.e. Lazy/Asynchronous Loading) with requirejs

Asynchronous module definition (AMD) is a JavaScript specification that defines an API for defining code modules and their dependencies, and loading them asynchronously if desired.Below are benefits of AMD:-

1)Application is broken in multiple smaller files,so only needed files are loaded at time.
2)AMD allows developers to define dependencies which must be loaded before module is executed.
3)If you are working with big applications then by module you have to work one by one and you don’t have to
remember the logic of entire application at one time.
4)AMD specification is implemented by Dojo Toolkit, RequireJS.

We will be see practically why and when to use this.

Lets create a use case.
1)In a family there is one child and his mother and father.
2)One question is asked to child which he have to reply in just true or false.
3)Child will reply after asking to his mother and father.
4)For replying to child his father will also ask to his mother.

Now lets code for this small scenario.

Create folder with name ‘js’ in application and create all .js files inside this folder. Now lets create classes for this use case one by one :-
1)index.html:-

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo For AMD with requirejs</title>
</head>
<body>
<h2>For detail info Check console and js files for watching details.</h2>


<!-- Script no. 1 -->
<script src="js/mother.js"></script> 

<!-- Script no. 2 -->   
<script src="js/father.js"></script>

<!-- Script no. 3 -->  
<script src="js/boy.js"></script>

<!-- Script no. 4 -->
<script src="js/main.js"></script>

<script data-main="js/main" ></script>

</body>
</html>

2)main.js:-

var result = askToBoy();
if(result){
alert("Your Question is answered as " + result);
}

3)boy.js:-

function askToBoy()
{
console.log("Function : askToBoy()");

var fatherResponse = fatherReply();
if(fatherResponse){
var motherResponse = motherReply();
if(motherResponse){
return true;
}
else{
return false;
}
}
else{
return false;
}
}

4)father.js:-

function fatherReply(){
"use strict";
console.log("Function : fatherReply()");

var fatherResponse = wifeReply();
return fatherResponse;
}

5)mother.js:-

function motherReply(){
console.log("Function : motherReply()");

myRepsonse = true;
return myRepsonse;
}

function wifeReply(){
console.log("Function : wifeReply");

myRepsonse = true;
return myRepsonse;
}

Now run the application it will give you “true” as result in alert.
Now in index.html just shift line :-

<script src="js/main.js"></script>

to 1,2 or 3 lines up.Now you will see that this is not running no alert is coming and giving exception in code(check console).
Here you can see that there is no way of knowing dependency of knowing any class.For a big application we can not rely on this style.And if with a lot of caring we will code then also it will be loading a lot of files and hence the performance will be decrease.

Now Lets start with AMD style.
First of all get the require.js file from link below :-
http://requirejs.org/docs/download.html#requirejs

Create folder with name ‘js’ in application and create all .js files inside this folder including downloaded ‘require.js’. Now Create classes one by one as below:-

1)index.html:-

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Asynchronous Module Definition( i.e. Lazy/Asynchronous loading) with requireJS </title>
</head>
<body>

<h2>Asynchronous Module Definition( i.e. Lazy/Asynchronous loading) with requireJS </h2>
<h2>For detail info Check Console.</h2>

<script data-main="js/main" src="js/require.js"></script>
</body>
</html>

2)main.js:-

require(["boy"],function(boy){
"use strict";
var result =  boy.askToBoy();

alert("Response to your question is "+ result);

});

3)boy.js:-

define(["father","mother",console], function(father,mother) {
"use strict";
console.log("boy class.");

return {
askToBoy : function() {
var boyResponse = father.fatherReply() && mother.motherReply();
return boyResponse;
}
};
});

4)father.js:-

define(["mother",console], function(mother) {
"use strict";
console.log("class father");

return {
fatherReply: function() {
var wifeResponse = mother.wifeReply();
return wifeResponse;
}
};
});

5)mother.js:-

define([console],function() {
"use strict";
return {
motherReply: function() {
console.log("mother class's motherReply function.");
return true;
},

wifeReply:function() {
console.log("mother class's wifeReply function.");
return true;
}
};
});

Now you can see that using ‘requirejs’ for AMD style application, we are able to provide the dependency of each and every module at it’s inner level.So as the classes will be require by application those will be served accordingly.And hence the load of application will be also less and we will able to optimize performance also.

This approach will be provide much better result as much as big application you will be having.

Hope this will helpful for someone.

npm ERR! Windows_NT 6.1.7601 Error with nodejs Command

You may found this error when you are trying to install any tool based on nodejs.
The reason for this is that you are not able to connect to the repo from your machine due to any proxy or firewall.
But the another thing which I want to mention for my case was that I was not running the command prompt as Administrator.
Once I run same command with Administrator right, after opening command prompt it worked perfectly.

Hope this can help full for someone.

Why NodeJS For Client Side Java Script Developers ?

Most of the tech community is aware that nodejs for the server side development with java-script but very less are aware that Nodejs is one of important technology for client side developers. The reason for this is that multiple client side develpment tools runs on this. Bower, Gulp, Grant etc. are some of those. So Client side java script developer must need nodejs on his machine as these tools are on top of nodejs.

You can get nodejs from the link below:-

https://nodejs.org/en/

Hope this will help someone.

Creating Responsive Single Page Application with Angular JS

In this sample we will be just creating a sample structure with very simple features. You have gone through multiple samples, but trying to put things together for creating at least a small structure of multiple components. Let’s consider a case that one will be just having some static pages and header and footer for application.
So we can say that we will be having multiple tabs in application and will also making a tab, which will having drop-down menus. In this sample we will be using controllers just to show how those are written. Will not creating any modules here.Things will be help full for later stages with this sample. Also this sample will be more helpful for beginners and designers mainly. We are using bootstrap css for the responsive design.

Let’s first create index.html of application as below:-

<!DOCTYPE html>
<html>
<head>
<title>SPA with Angular</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>

<!-- Add jQuery and Bootstrap. -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<!-- Add angularjs -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>

<!-- Add application's JS File -->
<script src="js/app.js"></script>

<body ng-app="spaWebApp">
<div ng-include='"header.html"'></div>
<div ng-view=""></div>
<div ng-include='"footer.html"'></div>
</body>

</html>

As you can see that page have below main parts:-
1) Adding jQuery,Bootstrap and angular references.
2) Adding ‘app.js’
3) Added three divs for header,footer and content of application.

Now below is code of app.js:-

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

/**
* Configure the Routes.
*/
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// Home.
.when("/", {templateUrl: "pages/home.html", controller: "HomeController"})

// Tabs.
.when("/tab1", {templateUrl: "pages/tab1Ui.html", controller: "TabController"})
.when("/tab2", {templateUrl: "pages/tab2Ui.html", controller: "TabController"})
.when("/tab3", {templateUrl: "pages/tab3Ui.html", controller: "TabController"})

// Menu Items.
.when("/tab4/menu1", {templateUrl: "pages/tab4menu1Ui.html", controller: "MenuController"})
.when("/tab4/menu2", {templateUrl: "pages/tab4menu2Ui.html", controller: "MenuController"})

//page not Found.
.otherwise("/404", {templateUrl: "pages/errorpage.html", controller: "PNFController"});
}]);

app.controller('HomeController', function (/* $scope, $location, $http */) {
document.getElementById("msglbl").innerHTML = "HomeController Working Fine.";
});

app.controller('TabController', function (/* $scope, $location, $http */) {
document.getElementById("msglbl").innerHTML = "TabController Working Fine.";
});

app.controller('MenuController', function (/* $scope, $location, $http */) {
document.getElementById("msglbl").innerHTML = "MenuController Working Fine.";
});

app.controller('PNFController', function (/* $scope, $location, $http */) {
document.getElementById("msglbl").innerHTML = "PNFController Working Fine.";
});

For this sample you don’t need to focus a lot on multiple controllers.But you can see how controllers can be associated with multiple parts of application.In this sample we are just changing the text of footer as via multiple controllers.

As per above code you will need to create header and footer templates and multiple pages inside ‘pages’ folder.Instead of providing code of multiple pages just adding sample html for ‘home.html’.You can create all pages as per your requirement.Below is structure for ‘home.html’:-

<div class="container" >
<div class="jumbotron" style="width: 100%;height: 100%" align="center">
This is Home page.
</div>
</div>

Here is ‘header.html’:-

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#/">Home</a></li>
<li><a href="#/tab1">Tab1</a></li>
<li><a href="#/tab2">Tab2</a></li>
<li><a href="#/tab3">Tab3</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Tab4(with Menus) <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#/tab4/menu1">Menu1</a></li>
<li><a href="#/tab4/menu2">Menu2</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>

and the last one is ‘footer.html’:-

<footer>
<div align="center">
<p>This is your footter.</p>
<p id="msglbl" style="color: #0000ff"></p>
</div>
</footer>

Except these files you will see some pages referenced in app.js. Those are simple pages lot like similar to ‘home.html’.
You can design them later according to your needs later on.

Hope this will be useful for someone.

First AngularJS Sample Application

We will be creating our first angularJS application as very basic sample app.As AngularJS is a javascript framework and written in javascript,so it is distributed as a javascript file.We can simply add it inside     ‘<script>’ tags.

Now as AngularJS extends HTML with ng-directives.For our this sample we will be using below 4 angular directives:-
1)ng-app :- which defines an AngularJS application.
2)ng-model :-which binds value of HTML control e.g. ‘input’ to application’s data.
3)ng-bind :- this directive binds application’s data to HTML view.
4)ng-init :- this directive is used to initialize AngularJS application variables.

Attaching code for the this application and we are ready to go.

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<body>
  
<div ng-app="" ng-init="modelname='David'">
 
  <p>Enter Name Here: <input type="text" ng-model="modelname"></p>
  <p ng-bind="modelname"></p>
 
 
</div> 
</body>
</html>

Hope this will help someone.