into Angularjs (vi) Services

Source: Internet
Author: User

Today I studied Ng's service mechanism, as one of the basic knowledge of NG, it is necessary to do an understanding, here to make a note to record.

I. Understanding Services (Service)

Service This concept is not unfamiliar, in other languages such as Java has such a concept, its role is to provide a specific function, such as message services, file compression services, etc., is a separate module. The service of NG is defined as:

Angular Services is singletons objects or functions that carry out specific tasks common to web apps.

It is a singleton object or function that provides specific functionality to the outside.

    • The first is a singleton, that is, the object always has only one instance, regardless of whether the service is injected anywhere.
    • Second, this is different from defining a function for ourselves and then calling it elsewhere, because the service is defined in a module, so its scope of use can be managed by us. Ng has a strong sense of avoiding global variables pollution.

NG provides a number of built-in services that can be viewed in the API http://docs.angularjs.org/api/. Knowing the concept, let's pull out a service to sneak out and see what the usage is. (from the beginning of this article, I will use Jsfiddle to write the sample code, no longer toss the blog Garden of the Metamorphosis editor ~)


We directly declare the $location service in the controller, which relies on Ng's dependency injection mechanism. $location provide the address bar related services, we are here simply to get the current address.

The use of services is so simple that we can inject services into controllers, instructions, or other services.

Second, custom services

As with directives, the services built into the system start with $, and we can define a service ourselves. There are several ways to define a service:

    • Using the system's built-in $provide service
    • Factory method for using module
    • Service methods using the module

Here is a small example to test separately. We define a service called RemoteData, which can fetch data remotely, which is a feature we use frequently in our programs. But I do not have a remote server here, just write a little bit of data simulation.


// use $provide to define var function ($provide) {    function() {        var data = {name: ' n ', value: ' V '};        return data;    });


// Use the Factory method app.factory (' remotedata ',function() {    var data = {name: ' n ', value: ' V '};    return data;});


// Use the Service method App.service (' remotedata ',function() {This    . Name = ' n ';    this. Value = ' V ';});

Module's factory and $provide's factory method is identical, from the official website document to see them is actually one thing. As for how the module inside is called, I'm not going to delve into it here, I just need to know how to use it.

Looking at the service method of module, it does not return anything because the service method itself returns a constructor that automatically uses the new keyword to create an object. So we see that this can be used within the constructor function, so that the data can be accessed directly from the remotedata.name where the service is invoked.

Let's use our own defined services:


Iii. the dependency relationship of management services

There can be dependencies between services and services, for example, we define a service called validate, whose role is to verify that the data is legitimate, and that it relies on our service RemoteData to get the data remotely. The code is as follows:


In the factory parameter, we can directly pass in the service Remotedata,ng's dependency injection mechanism to help us do the other work. However, make sure that the name of this parameter is the same as the service name, and that Ng is identified by name. If the position of the parameter is inconsistent with the service name, you must display the statement as follows:


App.factory (' Validate ', [' remotedata ',function(remotedataservice) {    returnfunction () {        if(remotedataservice.name== ' n ') {            alert (' Validation passed ');        }    };}]);

The same is true when we inject services into a controller, and the name you use needs to be consistent with the name of the service to inject correctly. Otherwise, you must use $inject to manually specify the injected service. Like what:


function TESTC (scope,rd) {    function() {        alert (' Name: ' +rd.name+ '   value: ' +rd.value ');}    } TESTC. $inject = [' $scope ', ' RemoteData '];

-------------------added to 2014.01.11-------------------------

Thanks to @terry Sun, it is also possible to inject services into a controller and use an array as a second parameter when defining a controller, to inject services into it here, and to use inconsistent service names in the body of the function, but to ensure that the order of injections is consistent, Such as:


App.controller (' TESTC ', [' $scope ', ' remotedata ',function($scope, RD) {    function() {        Alert (' Name: ' +rd.name+ '   value: ' +rd.value ');}    ]);

The basic knowledge of NG services is the same. At present, just learn some fur, perhaps later in the project to realize the strength of his, as well as in the real use of such problems.


Source: http://www.cnblogs.com/lvdabao/p/3464015.html



From for notes (Wiz)

into Angularjs (vi) Services

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.