Search This Blog

2016-01-11

Angular JS Tutorial9: services,factory,provider

AngularJS Service, Factory or Provider all are used for the same purpose of creating utility function that can be used throughout the page with inject-able object. However, the way it is created and the way it is used are different. Here we shall try to understand them clearly.


AngularJS Service:
Angular Service is used to for sharing utility functions with the service reference in the controller. Service is singleton in nature so for once service only one instance is created in the browser and the same reference is used throughout the page.In the service, we create function names as property with this object.

AngularJS Factory :
The purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.

AngularJS Provider:
The purpose of this is again same however Provider gives the output of it's $get function.

Example :

9.html:

<!DOCTYPE html>
<html lang="en">
<head>
 <title>services,factory,provider</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="9controller.js"></script>

</head>
<body ng-app="myapp" ng-controller="mycontroller">
 {{mymessage}}

</body>
</html>

9controller.js:
var app=angular.module('myapp',[]);

app.service('myservice',function(){
 this.mymessage='this is from my service';
}
);
app.factory('myfactory',function(){
 var factory={};
 factory.mymessage='this is from my factory';
 return factory;
}
);
app.provider('myprovider',function(){
 var m1='this is from my provider';
 return {
  setMessage:function(name){//1)its required,if we need set the value
   m1 += name;
  },
  $get:function(){
   return {
    message:m1
   }
  }
 }
});
//2)its required,if we need set the value
app.config(function(myproviderProvider){//ProviderSuffix
 myproviderProvider.setMessage("Manab");
});
app.controller('mycontroller',function($scope,myservice,myfactory,myprovider){
 $scope.mymessage=[myservice.mymessage,myfactory.mymessage,myprovider.message];
});
// app.controller('mycontroller',function($scope,myservice,myfactory){
//  $scope.mymessage='ddd';
// });


Output:


Angular JS Tutorial8: $digest and $watch

$digest() is useful when we want to hook up a vanilla javascript in angularjs.

When you create a data binding from somewhere in your view to a variable on the $scope object, AngularJS creates a "watch" internally. A watch means that AngularJS watches changes in the variable on the $scope object. The framework is "watching" the variable. Watches are created using the $scope.$watch() function


<!DOCTYPE html>
<html lang="en" >
<head>
 <title>$digest,$watch</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

 <script type="text/javascript">
  var application=angular.module('myapp',[]);
  application.controller('mycontroller',function($scope)
  {
   $scope.myRandomNumber=Math.random();
   $scope.counter=-1;
   document.querySelector('input').addEventListener('click',function(){
    $scope.myRandomNumber=Math.random();
    $scope.$digest();
    $scope.$watch('myRandomNumber',function(newValue,oldValue)
    {
     if($scope.counter==5)
      alert('You reach at 5');
     $scope.counter++;
    }
    );
   },false);
  }
  );
 </script>
</head>
<body ng-app="myapp" ng-controller="mycontroller">
 {{myRandomNumber}}
 <br/>
 <input type="button" value="Generate Random Number"/>
</body>
</html>


Angular JS Tutorial7: http service and Search Filter

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.

Example :

Create a sample data file 7data.json as below
{
 "customers":[
  {
  "Name":"Steve",
  "Age":"30",
  "Location":"eastleigh"
  },
  {
   "Name":"Ari",
   "Age":"40",
   "Location":"eastleigh"
  },
  {
   "Name":"Clare",
   "Age":"35",
   "Location":"hedgeend"
  },
  {
   "Name":"Stu",
   "Age":"20",
   "Location":"southampton"
  }
   ]
}

7.html:
<!DOCTYPE html>
<html lang="en" >
<head>
 <title>$http,searchFilter</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="7controller.js"></script>
</head>
<body ng-app="myapp">
 <div ng-controller="mycontroller">
  <ul>
   <h2>Customer Details</h2>
   Any Search:<input type="text" ng-model="searchcriteria.$"></br></br>
   Name Search:<input type="text" ng-model="searchcriteria.Name"></br></br>
   Age Search:<input type="text" ng-model="searchcriteria.Age"></br></br>
   Location Search:<input type="text" ng-model="searchcriteria.Location"></br></br></br>
   <li ng-repeat="customer in customerdata|filter:searchcriteria">
  
     {{"Name:"+customer.Name+" Age:"+customer.Age +" Location:"+customer.Location}},
   
   </li>
  </ul>
 </div>
</body>
</html>

7controller.js :
var app=angular.module('myapp',[]);
app.controller('mycontroller',function($scope,$http){
 $http.get('http://localhost:8080/7data.json')
 .success(function(response)
 {
  $scope.customerdata=response.customers;
 }
 );
}
);

Output :



Angular JS Tutorial6: Login page using routeScope,check,resolve,location

We can control login/authorization using routeScope,check,resolve,location.

Example :

6.html :

<!DOCTYPE html>
<html lang="en">
<head>
 <title>routeScope,check,resolve,location</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="angular-route.js"></script>
 <script src="6controller.js"></script>
</head>
<body  ng-app="myapp">
 <div ng-view></div>
</body>
</html>

6controller.js :

var app=angular.module('myapp',['ngRoute']);
app.config(function($routeProvider){
 $routeProvider
 .when('/',{
  templateUrl:'6login.html',
  //template:'Loaded from /'
 })
 .when('/dashboard',{
  resolve:{
   "check":function($location,$rootScope){
    if(!$rootScope.loggedIn)
    {
     $location.path('/');
    }
   }
  },
  templateUrl:'6dashboard.html'
 })
 .otherwise({
  redirectTo:'/'
 });
});
app.controller('loginCtrl',function($scope,$location,$rootScope){
 $scope.submit=function(){
 

  if($scope.username=='Admin' && $scope.password=='Admin'){
   $rootScope.loggedIn=true;
  
   $location.path('/dashboard');
  }
  else{
   alert('wrong credential');
  }
 };
});

6login.html :

<div ng-controller="loginCtrl">
 <form action="/" id="myloginform">
  User Name : <input type="text" ng-model="username" id="username"/><br/>
  Password : <input type="password" ng-model="password" id="password"/>
  <button type="button" ng-click="submit()">Login</button>
 </form>
</div>

6dashboard.html :

Welcome to Dashboard

Angular JS Tutorial5: ngroute

The ngRoute module provides routing for angular apps.

We can download angular-route.js from the below location
e.g. //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js
where x.y.z indicates the version on angular-route.js like 1.3.5

Example :

5.html:

<!DOCTYPE html>
<html lang="en">
<head>
 <title>ngRoute</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="angular-route.js"></script>
 <script src="5controller.js"></script>
</head>
<body  ng-app="myapp">
 <div ng-view></div>
</body>
</html>

5controller.js :

var app=angular.module('myapp',['ngRoute']);
app.config(function($routeProvider){
 $routeProvider
 .when('/',{
  templateUrl:'5a.html',
  //template:'Loaded from /'
 })
 .when('/fiveb',{
  templateUrl:'5b.html'
 })
 .when('/fivec',{
  templateUrl:'5c.html'
 })
 .otherwise({
  redirectTo:'/'
 });
});

5a.html:
I am in 5a<a href="#/fiveb">Open fiveb</a>

5b.html:
I am in 5b

5c.html:

<a href="#/fiveb">Open fiveb</a>I am in 5c



Angular JS Tutorial4: ng-include

ng-include fetches, compiles and includes an external HTML fragment.

Example:
<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
 <title>ng-includes</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
 <div ng-include="'4a.html'"></div> <!-- Need localhost to test this example -->
</body>
</html>

Angular JS Tutorial3: ng-controller,filter

The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.

MVC components in angular:

•Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties are accessed through bindings.

•View — The template (HTML with data bindings) that is rendered into the View.

•Controller — The ngController directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values.

Filter selects a subset of items from array and returns it as a new array.

Example :

<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head>
 <title>ng-controller,filter</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>
<body>
 <div ng-controller="mycontroller">
  {{mylanguage|uppercase}}
  <button ng-click=changelang()>Change Language to Bengali</button>
 </div>

 <script type="text/javascript">
  var application=angular.module('myapp',[]);//[] : use for referring other module
  application.controller('mycontroller',function($scope)
  {
   $scope.mylanguage='English';
   $scope.changelang=function(){
    $scope.mylanguage='Bengali';
   }
  }
  );
 </script>
</body>
</html>


Output:

Angular JS Tutorial2: ng-init,ng-repeat,sharedscope

The ng-init directive initializes application data.

The ngRepeat directive instantiates a template once per item from a collection.

In order to share data between scopes by model, use the model property like samplemode.sampledata

Example :

<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
 <title>ng-init,ng-repeat,sharedscope</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>
<body>
 <div ng-init="menu='chicken';
 places=[
 {country:'UK',city:'Southampton'},
 {country:'Europe',city:'Paris'},
 {country:'India',city:'Kolkata'},
 ]">
  <input type="text" ng-model="menu"/>
 </div>
<br/>
Share the data between this textbox and textboxes inside the country:city loop use the property like 'message.sharescope'<br/>
Otherwise it will be unidirectional binding from outer ti inner loop, when you use only 'message'<br/>
<input type="text" ng-model="message.sharescope"/><!--to share data between scope, use the property like 'message.sharescope' inplace of 'message', else innser scope value will not be passed to outer scope-->
<p ng-repeat="place in places">
 {{place.country}} :{{place.city}}
 <input type="text" ng-model="message.sharescope">
 <br/>
</p>
</body>
</html>


Output


2016-01-05

Angular JS Tutorial1: ng-model,ng-bind and Expression

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
Typically, we don't use ngBind directly, but instead you use the double curly markup like {{ expression }} which is similar but less verbose.

It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before Angular compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

Example:

Before staring Angular Expression, create the web server using node.js with the below file

1)Package.json:

{
  "name": "angulardetails",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies" : {
    "connect"         : "*",
    "serve-static"    : "*"
 
  }
}

2)index.js

var connect=require("connect");
var serveStatic=require("serve-static");

var app=connect()
.use(serveStatic('public'))
.use(function  (req,res) {
res.end("Welcome to the Static Demo");
})
.listen(8080);

console.log("listening from port 8080");

3)Create a public folder in the root.

4)run npm install to install dependencies

5)run using 'node index.js'

Now create angular.js file "1.html" with in the public folder


<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
<title>ng-model,ng-bind,Expression</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>
<body>
Info: ng-model works on input, ng-bind on div<br/>
<input type="text" ng-model="name"/>
<div >Hello {{name}}</div>

Hello <div ng-bind="name"></div>
<div data-ng-bind="name"></div>
<div ng:bind="name"></div>
<div ng_bind="name"></div>
<div >Expression {{10*12}}</div>
</body>
</html>


See your angular js file in browser by typing the URL "http://localhost:8080/1.html"