What is Angular Service Factory? Why and Where should we use it?

In our previous article we have discussed about Angular service. We have created service using .service() method. In this article we will discuss about angular service factory.

So, first things first, we need to know what is factory in Angular. We can create our own services by registering the service factory function. The service factory function generates the single object or function which represents the service to the rest of the application. The object or function returned by the service is injected into any component (controller, service, filter or directive) that specifies a dependency on the service. Each component dependent on a service gets a reference to the single instance generated by the service factory ,what we know as singletons. But when we declare a service using service() method, Angular only instantiates a service when a component depends on it – known as lazily instanitiated.

Now, let us see how we can create a factory.

[javascript]

var app=angular.module(‘myApp’,[‘ngRoute’]);

app.factory(‘ageService’, function ($rootScope) {
var ageObj = {
age:0,
saveAge: function (age) {
this.age=age;
$rootScope.$broadcast(‘ageAdded’);
},
getAge: function(){
return this.age;
}
};
return ageObj;
});

[/javascript]

Here we have created a factory called ‘ageService’. In this factory an object i.e. value is returned whenever we invoke it. This object contents properties(age) and functions(saveAge(), getAge()) together. This is the main diffrence with service created with service method. When we were using service() method a function was being instantiated. But here a value is returned by invoking the function reference passed to module.factory. And then we can use the functions with it’s reference.


 

Another thing we are using here is $rootscope. Every application has a single root scope and all other scopes are descendant scopes of the root scope. $rootScope basically functions as an event listener and dispatcher. $rootScope.$broadcast is a convenient way to raise a “global” event which all child scopes can listen for. We only need to use $rootScope to broadcast the message, since all the descendant scopes can listen for it. Let’s make it more clear by using the factory in our controller.

[javascript]

//Controllers
app.controller(‘saveController’,function($scope,ageService){
$scope.setAge=function(){
ageService.saveAge($scope.inputage);
};
$scope.$on(‘ageAdded’, function () {
$scope.status="Age Saved";
});
});

app.controller(‘displayController’,function($scope,ageService){
$scope.myage=ageService.getAge();
});

[/javascript]

In the above code we have used our ‘ageService’ in both the controllers, one for saving person’s age and another for getting age. Both of them have used the factory’s method in order perform their task. When $scope listen for the event ‘ageAdded’ it sets the status that age has been saved. We are routing our application in the following way.

[javascript]

app.config(function($routeProvider){
$routeProvider
.when(‘/’,{
templateUrl: ‘saveage.html’,
controller:’saveController’
})
.when(‘/displayage’,{
templateUrl: ‘displayage.html’,
controller:’displayController’
});
});

[/javascript]

Now let’s see the templates to get full transparency about the code we have used still now.

index.html
[javascript]

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Single Page Application using Angularjs</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.1/angular-route.min.js"></script>
<script src="js/script.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="saveController">
<div ng-view>
<!–This DIV loads templates depending upon route.–>
</div>
</div>

</body>
</html>

[/javascript]

savepage.html
[javascript]

<ul>
<li><a href="#/">Save Age</a></li>
<li><a href="#displayage">Display Age</a></li>
</ul>
<div>
<input type="text" ng-model="inputage">
<button ng-click="setAge()">Save</button>
<div>{{status}}</div>
</div>

[/javascript]

displayage.html
[javascript]

<ul>
<li><a href="#/">Save Age</a></li>
<li><a href="#displayage">Display Age</a></li>
</ul>
<div>
My Age={{myage}}
</div>

[/javascript]

So, by now it’s clear how we used our factory in this application. Look, we are getting the age exactly we saved though going to another page without using any localstorage or database. This is because we are saving it in the age property of our ageService factory.

Reader can download the full source code from Github.

If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:

Delivered by FeedBurner


 

Chinese Embassy in Ottawa issues statement advising Chinese

To convince Caylee that he isn’t lying he brings an elder lady, Gladys, to a fair to pretend to be his grandmother. Mac brings Caylee to the fair where they casually run in to Dennis. Meanwhile, Charlie plays a pitching game the Waitress is running at the fair.

iphone 8 case If you go with a third party, make sure it guarantees its work, says Ed Kuhner, vice president of customer experience for HTC Americas. And will come to you. They can usually swap out a screen in less than an hour, says spokesman Jack Murphy. This processing appears to allow the virus to bind to cellular proteins enabling it to fuse with internal cellular membranes and release the viral nucleocapsid. The structural glycoprotein (known as GP1,2) is responsible for the virus’ ability to bind to and infect targeted cells. The viral RNA polymerase, encoded by the L gene, partially uncoats the nucleocapsid and transcribes the genes into positive strand mRNAs, which are then translated into structural and nonstructural proteins. iphone 8 case

iPhone Cases Earlier this month, international media were granted rare access to the three detained Americans, who in separate interviews called on the United States to secure their release. Citizens to extract a high profile visit from Washington, with whom it has no formal diplomatic ties. Special envoy for North Korean human rights issues, to discuss Kenneth Bae’s case.. iPhone Cases

iphone 8 case Edit2: You getting a bit of grief from others on “that not the sane way to do that”, but I will at least step up and point out that your concept is great, your idea to implement it is where it falls flat, hence the suggestion of purpose built tools that exist to give exactly the benefits you after (and then some). I used git (and svn) for exactly that role on a personal machine or two over the years, before things like puppet, chef, and ansible really got to a point that I bother with them (back then, cfengine was the go to, and it. Was a bit of a beast for a small set of hosts).. iphone 8 case

iphone 8 case Or to any successor or future owner of its assets.In all of these cases, Self Improvement Online, Inc. Agrees to include your bio at the end of your article. No other use is implied or granted.. June 3: Reports that Magnotta stayed in low budget hotel in Paris, leaving behind pornographic magazines as well as air sickness bags from airplane. French media report police are checking on claims of two people who say they saw him. Chinese Embassy in Ottawa issues statement advising Chinese visitors to Canada to take safety precautions.. iphone 8 case

iphone 6 plus case The Supreme Court had accepted the argument that the due process clause protected the right to contract seven years earlier cheap iphone cases, in Allgeyer v. Louisiana (1897). However, the Court had acknowledged that the right was not absolute, but subject to the police power of the states. iphone 6 plus case

iphone 8 case DeJohnette also appears on Blue Maqams. The new album from Tunisian oud player and composer Anouar Brahem sees DeJohnette rejoining his old Miles Davis/Gateway bandmate, bassist Dave Holland, and pianist Django Bates for a trip through jazz variations of a North African vibe. As stated before, there is nothing the man doesn’t play.. iphone 8 case

iphone 6 plus case To be perfectly honest, Luke’s starting point in this movie was the only thing I was willing to predict out of TFA, and my guess turned out to be correct. I felt coming out of TFA that Luke was on that island because he was to some degree on the run and afraid, and that he would need to come back to fight in some capacity, And he would only do this for a personal connection, a love of someone close to him, probably Leia. Consequently, I suspected Leia would get hurt early in 8.. iphone 6 plus case

iPhone x case “I screwed the executive producer,” she says. His retort: “In the missionary position, I assume.”Dodgy repartee aside, Holmes is a man of many talents. Because he has succeeded so wildly and widely, you figure Holmes is some kind of genius. As is the case for many other suppliers cheap iphone cases, Wal Mart bought more than 20% of our product line, measured by sales volume. Any sign that Wal Mart might cut orders, or worse, drop a SKU (stock keeping unit) from its shelves, is enough to send shivers down my spine.For a typical visit to Bentonville, a supplier had to be careful to rent a modest car and live in modest accommodations, preferably EDLC motel chains like Motel 6 or at most, Days Inn. Renting a compact car would also be prudent. iPhone x case

iphone 8 plus case Told in just 75 minutes,The Glass Coffin is a thriller that will keep you on the edge of your seat. We start with Amanda in her car, clearly revelling in the grandeur of both her transport and the night. She chats away happily to her husband, cracking open the champagne whilst commenting on the free cocaine, but it isn long before her phone call is cut short and her real evening unfolds. iphone 8 plus case

iphone 8 case Filling out the strong cast Susan Sullivan portray’s Castle’s mom and Molly C. The pilot was well done by Andrew W. Marlowe, Barry Schindel, David Grae and Charles Murray. For more information on Adobe PDF and Microsoft Word files and how they are used on this site check the software information page. Standard court forms are also available in any county Clerk of Circuit Court office.How do I find and download forms?To find a listing of the standard mandated forms, please refer to the Wisconsin court system’s online indexes on the circuit court forms page. From that page, you can conduct a forms conceptual search or view two listings of forms iphone 8 case.

What is Angular Service? Why and where should we use it?

By definition services in AngularJS are Javascript functions that are responsible to do only specific tasks. Services can be used to organize and share code across an application. Here sharing refers to sharing of data and functions. It keeps data across the lifetime of an Angular app. Controller communication can be done using services in a consistent way. Angular services are substitutable objects that are wired together using dependency injection (DI).

Angular services are :
Lazily instantiated : A service is instantiated only using the $injector when an application component depends on it.
Singletons : Each component dependent on a service gets a reference to the single instance generated by the service factory.

AngularJs provides some inbuid services like $http, $route, $location etc. and each of them perform a specific task. For example $http is used to make ajax call to the server to get data, $route is used for routing application and so on. We can also create our own service for our purpose depending on the needs.

Creating service

Service can be created in several ways. They are :

  • using service() method
  • using factory() method
  • using provide() method
  • using constant() method
  • using value() method
  • In this article we are going to use the service() method. Using service() method we first define a service and then assign method to the service. Let’s take look at the following example.

    [javascript]

    var app = angular.module(‘myApp’,[]);

    app.service(‘myService’,function(){
    this.getLength=function(element){
    return element.length;
    };
    });

    [/javascript]

    Here we have created a service for myApp application named ‘myService’. The service has its own method getLength() that returns length of passed element. It’s very simple, right? Now let’s see how to use this service as well as the function within it.

    [javascript]

    app.controller(‘myController’,function($scope,myService){
    $scope.showLength=function(element){
    $scope.len=myService.getLength(element);
    };
    });

    [/javascript]


     

    In the above code snippet we are defining a controller for our application and injecting our myService in it. Then in $scope’s showLength() function (to be called from the template) we are using getLength() function of our service ‘myService’. As a result view is updated with the length. Let’s look at the view now.

    HTML Template
    [javascript]

    <html lang="en" ng-app="myApp">
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="js/script.js"></script>
    </head>
    <body>

    <div ng-controller="myController">
    <div ng-view>
    <div>
    <input type="text" ng-model="text1" ng-change="showLength(text1)" />
    </div>
    <div>
    Length : {{len}}
    </div>
    </div>
    </div>

    </body>
    </html>

    [/javascript]

    By now it is clear how we are calling the controller’s showLength() method. So we get the length of the textbox whenever we type or erase something in the input box.

    Dependencies

    Services can have their own dependencies. We can declare dependencies by specifying them in the service’s factory function signature like we use to do in controller.

    A simple example would be

    [javascript]

    app.service(‘myService’, [‘$interval’, function($interval) {


    $interval(function(){…},5000);

    }]);

    [/javascript]

    Here we have used $interval for dependency injection in our service and using it for performing some action to be taken place in an interval of 5 seconds.

    If you find this article helpful, you can connect us in Google+ and Twitter.

    Enter your email address:

    Delivered by FeedBurner


     

    What is Angular Controller? Why and where should we use it ?

    In MVC format application a controller is responsible for interacting between model and view. It facilitates to chage the state of the model. The main business operations in an MVC application is written inside a controller. In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope. It is responsible for data flow in the application.

    We can attach the controller to the DOM using ng-controller directive. Also we can set controller while routing in AngularJS(See Angular Routing Here). A controller is a JavaScript Object, created by a standard JavaScript object constructor. Angular will instantiate a new Controller object using the specified Controller’s constructor function when we attach it through ng-controller.

    Attacing controller through ng-controller

    [javascript]

    <div ng-controller="myController">

    {{message}}

    </div>

    [/javascript]

    Angular controller can be used to set the initial state of the $scope object and add behaviour to it. It should not be used to format input, filter output, manipulate DOM etc. so that it’s testability does not get affected.

    We need to set up the initial state of the $scope object by attaching properties to it.Let’s take a look how we set initial state of $scope object in the following example.
    [javascript]

    var app = angular.module(‘myApp’,[]);

    app.controller(‘myController’, [‘$scope’, function($scope) {
    $scope.message = ‘Hello John’;
    }]);

    [/javascript]

    Here we are creating an Angular module called app and adding the controller’s constructor function using .controller() method. The message property is now data bound to the template.

    Next we will add some behaviour in order to react to events and computational purpose. Adding behaviour means adding methods to controllers. Those methods can be invoked via Angular expressions or events(for example ng-click,ng-show etc.) in templates. Check out our example below.

    [javascript]

    app.controller(‘myController’, [‘$scope’, function($scope) {
    $scope.message = ‘No message’;
    $scope.showMsg()=function(){
    $scope.message = ‘Hello World’;
    };
    }]);

    [/javascript]

    Here in myController we have created a method showMsg() and attached to the $scope. Now we will invoke it in our template.

    [javascript]

    <div ng-controller="myController">
    <div>{{message}}</div>
    <div><button ng-click="showMsg()">Show Message</button></div>
    </div>

    [/javascript]

    When the button is clicked the message changes from ‘No message’ to ‘Hello World’ as defined in our method showMsg(). Okay, that was simple enough. Let’s do some interesting thing.


     

    index.html
    [javascript]

    <html ng-app="myApp">
    <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
    <div ng-view>
    <div ng-controller="myController">
    <input type="text" ng-model="textbox" ng-change="changeStatus()" />
    <button ng-show="!empty" ng-click="clear()">Clear</button>
    <div>
    </div>
    </body>
    </html>

    [/javascript]

    script.js
    [javascript]

    var app = angular.module(‘myApp’,[]);

    app.controller(‘myController’, [‘$scope’, function($scope) {
    $scope.empty=true;
    $scope.changeStatus=function(){
    var len=$scope.textbox.length;
    $scope.empty=len>0?false:true;
    };
    $scope.clear=function(){
    $scope.empty=true;
    $scope.textbox=”;
    };
    }]);

    [/javascript]

    Isn’t it cool? The button hides when there is nothing in the input box and appears when we write something in it. The changeStatus() is attached to the $scope that fires whenever some changes occurs in the textbox as it is set to the ng-change directive and performs accordingly by setting empty property of the $scope and counting it’s length. The clear() method clears the input box and resets the empty property to true.

    Scope inheritence

    We can attach controllers at different levels of DOM hierarchy using ng-controller as it creates child scope where it is declared. The nested controller or child controller can access(inherits) the properties as well as the methods of it’s parent’s controller. If it doesn’t make a sense to you, look at the following example.

    HTML Template
    [javascript]


    <div ng-controller="firstController">
    Name = {{name}} Age = {{age}}
    <div ng-controller="secondController">
    Name = {{name}} Age = {{age}}
    </div>
    </div>

    [/javascript]

    script.js
    [javascript]

    var app = angular.module(‘myApp’,[]);

    app.controller(‘firstController’, [‘$scope’, function($scope) {
    $scope.name=’John’;
    $scope.age=30;
    }]);

    app.controller(‘secondController’, [‘$scope’, function($scope) {
    $scope.name=’Peter’;
    }]);

    [/javascript]

    Running this code in web server outputs :

    Name = John Age = 30
    Name = Peter Age = 30

    See, here we have defined the age property of $scope in firstController, not in secondController. But we get age as 30 in secondController when it outputs. This is because of being child of firstController, it inherits the $scope properties and methods. As it defines the name property so the name is overwritten.

    If you find this article helpful, you can connect us in Google+ and Twitter.

    Enter your email address:

    Delivered by FeedBurner


     

    What is Angular router? Why and where should we use it?

    Routing helps us to divide our application in parts logically, making it more manageable. Whenever an app grows by adding logic into it it becomes hard to control and manage. Using routing we can easily divide our application in logical views. Routing also helps to bind different views to the controllers.

    The above picture shows two route URLs (#Link1,#Link2). When they are referred, the views(View 1,View 2) and controllers(Controller 1,Controller 2) loaded accordingly. Does it make any sense to you? Don’t worry ,let’s have a look at the following example.


     

    index.html
    [javascript]

    <html ng-app="myApp">
    <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.4.1/angular-route.min.js"></script>
    <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>

    <div ng-controller="firstController">
    <div ng-view>
    </div>
    </div>

    </body>
    </html>

    [/javascript]

    In the above code we can see we have included angular-route.min.js(or you can choose angular-route.js) for routing. This is required for including ngRoute module in our app. The ngRoute module provides routing and deeplinking services and directives for angular apps.

    first.html(Template)
    [javascript]

    <ul>
    <li><a href="#first">First Page</a></li>
    <li><a href="#second">Second Page</a></li>
    </ul>
    <h3>First Page</h3>

    [/javascript]

    second.html(Template)
    [javascript]

    <ul>
    <li><a href="#first">First Page</a></li>
    <li><a href="#second">Second Page</a></li>
    </ul>
    <h3>Second Page</h3>

    [/javascript]

    Above two html files are templates which will be loaded as per routed to links. Next we will see the Javascript i.e. main portion of our app where routing is being done. We have included script.js as we can see in index.html for javascript code. Let’s have a look.

    script.js
    [javascript]

    var app=angular.module(‘myApp’,[‘ngRoute’]);
    app.config(function($routeProvider){
    $routeProvider
    .when(‘/’,{
    templateUrl: ‘first.html’,
    controller:’firstController’
    })
    .when(‘/first’,{
    templateUrl: ‘first.html’,
    controller:’firstController’
    })
    .when(‘/second’,{
    templateUrl: ‘second.html’,
    controller:’secondController’
    });
    });
    app.controller(‘firstController’,function($scope,$route){
    //Controller code for firstController
    });
    app.controller(‘secondController’,function($scope,$route){
    //Controller code for secondController
    });

    [/javascript]

    Here we are installing ngRoute module first in our app. Then comes the configuration part where we are using $routeProvider. It is the service provider provided by the Angular which is actually responsible for taking care of routing. $routeProvider is the provider of the $route service by which we define the application routes in Angular. This service is used in order to wire together controllers, view templates, and the current URL location in the browser. We can implement deep linking using this feature in order to utilize the browser’s history and bookmarks.

    According the example, we set when the URL is root(‘Application/’) or ‘Application/first’ it loads ‘first.html’ template in ng-view as view and ‘firstController’ as controller. Similarly ‘second.html’ and ‘secondController’ are mapped as template and view respectively when the URL ‘Application/second’ is referred. We have put the links in template html files manually in order to test them easily using hastag (#first,#second). ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

    So that was a brief discussion on Angular router and its use in a web application. If you find this article helpful, you can connect us in Google+ and Twitter.

    Enter your email address:

    Delivered by FeedBurner