Angularjs Advanced (40) Create modules, services

Source: Internet
Author: User
Tags event listener

Angularjs Advanced (40) Create modules, services Learning Essentials

Using a modular architecture application

Creating and using Services

Why use and create services and modules?

Services allow you to package reusable features so that they can be used in this application.

Modules allow you to package reusable features so that they can be used across applications.

first, the application of modular

Let's look at a program that's not modular.

<! doctype><!--Use module-->

Click the city button to increment the total number of clicks


Next, we'll separate the instructions and make them modular, and we'll name it tributtondirective.js .

Angular.module ("Tributtondir", [])    . Directive ("Tributton", function () {        return {            //Isolation scope//            bidirectional data binding            scope: {                counter: "=counter"            },            //Chain function            link:function (scope, element, attrs) {                //Click event Listener, Print day Remember, calculate the cumulative                element.on ("click", Function (e) {                    console.log ("button click:" + e.target.innertext);                    Scope. $apply (function () {                        scope.counter++;})})}    )

Next, reference the defined label and use it

<!--introduction of Directive files--><script type= "Text/javascript" src= "Js/tributtondirective.js" ></script><script Type= "Text/javascript" >//use command Angular.module ("Exampleapp", ["Tributtondir"])

Second, create the use of services1. using the Factory method

First step: modularize the service, create a file named tributtonfactory.js

Angular.module ("Tributtonfactory", [])    . Factory ("Logservice", function () {        var messagecount = 0;        return {            log:function (msg) {                console.log ("(log +" + messagecount++ + ")" + msg);}}    )

Step Two: Introduce the service in the view

<script type= "Text/javascript" src= "Js/tributtonfactory.js" ></script>

Step three: Use it in the controller

Parameter Dependency Injection Angular.module ("Exampleapp", ["tributtondirective", "Tributtonfactory"])    //As a parameter to the controller    . Controller ("Defaultctrl", Function ($scope, logservice) {        //Data Model        $scope. "//"            City            Cities: [" London "," New York "," Paris "],            //Click Total            totalclicks:0        };        Add listeners to trigger the factory function $scope when the total number        of clicks changes. $watch ("Data.totalclicks", function (newval) {            //Console.log (" Click Count: "+ newval);            Use custom service            logService.log ("Total click Count:" + newval);        })    

2. using the service method

First step: Create the constructor and create the service. Our name is tributtonservice.js .

var Baselogger = function () {    this.messagecount = 0;    This.log = function (msg) {        Console.log (This.msgtype + ":" + (this.messagecount++) + "+ msg);}    } var Debuglogger = function () {};d Ebuglogger.prototype = new Baselogger ();d ebugLogger.prototype.msgType = "Debug"; var err Orlogger = function () {};errorlogger.prototype = new Baselogger (); errorLogger.prototype.msgType = "Error"; Angular.module ("Tributtonservice", [])    . Service ("Logservice", Debuglogger)

Step two: Introduce the tributtonservice.js file and then use the service

<! doctype><!--Use module-->

3. using the Provider method

First step: Create a service using Provider. Our name is tributtonprovider.js .

Angular.module ("Tributtonprovider", []). Provider ("Logservice", function () {var counter = true;        var debug = true;                    return {messagecounterenabled:function (setting) {if (angular.isdefined (setting)) {                    counter = setting;                return this;                } else {return counter;                    }}, Debugenabled:function (setting) {if (angular.isdefined (setting)) {                    debug = setting;                return this;                } else {return debug; }},//To return the service object $get: function () {return {MESSAGEC ount:0, Log:function (msg) {if (debug) {Console . log ("(log" + (counter?                        "+" + this.messagecount++ + ")": ")" + msg ");      }              }                }            }        }    }) 

Step two: Introducing, configuring, and using Services

<! doctype><!--Use module-->American and American Pictures

Angularjs Advanced (40) Create modules, 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.