加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS 模块服务 珠联璧合

发布时间:2020-12-17 10:07:08 所属栏目:安全 来源:网络整理
导读:学习要点 使用模块构架应用 创建和使用服务 为什么要使用和创建服务与模块? 服务允许你打包可重用的功能,使之能在此应用中使用。 模块允许你打包可重用的功能,使之能跨应用使用。 一、应用程序模块化 先看看一个没有模块化的程序 !DOCTYPE !-- use module

学习要点

  • 使用模块构架应用
  • 创建和使用服务

为什么要使用和创建服务与模块?
服务允许你打包可重用的功能,使之能在此应用中使用。
模块允许你打包可重用的功能,使之能跨应用使用。

一、应用程序模块化
先看看一个没有模块化的程序

<!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> </head> <body ng-controller="defaultCtrl"> <div class="well"> <!-- 使用自定义指令 --> <div class="btn-group" tri-button counter="data.totalClicks"> <!-- 遍历按钮 --> <button class="btn btn-default" ng-repeat="city in data.cities"> {{city}} </button> </div> <h5>Total Clicks: {{data.totalClicks}}</h5> </div> <script type="text/javascript" src="js/angular.min.js"></script> <script type="text/javascript"> angular.module("exampleApp",[]) .controller("defaultCtrl",function ($scope) { // 数据模型 $scope.data = { // 城市 cities : ["London","New York","Paris"],// 点击总数 totalClicks : 0 }; // 添加监听器,当点击总数发生变化时触发工厂函数 $scope.$watch("data.totalClicks",function (newVal) { console.log("Total click count: " + newVal); }); }) // 定义指令 .directive("triButton",function () { return { // 隔离作用域 // 双向数据绑定 scope : { counter : "=counter" },// 链式函数 link : function (scope,element,attrs) { // 点击事件监听,打印日记,计算累加 element.on("click",function (e) { console.log("Button click: " + e.target.innerText); scope.$apply(function () { scope.counter++; }) }); } } }) </script> </body> </html>

单击城市按钮,递增点击总数

接下来,我们将指令分离,使之模块化,我们命名为triButtonDirective.js

angular.module("triButtonDir",[])
    .directive("triButton",function () {
        return {
            // 隔离作用域
            // 双向数据绑定
            scope : {
                counter : "=counter"
            },// 链式函数
            link : function (scope,attrs) {
                // 点击事件监听,打印日记,计算累加
                element.on("click",function (e) {
                    console.log("Button click: " + e.target.innerText);
                    scope.$apply(function () {
                        scope.counter++;
                    })
                });

            }
        }
    })

接下来,引用定义的标签并且使用它

<!-- 引入指令文件 -->
<script type="text/javascript" src="js/triButtonDirective.js"></script>
<script type="text/javascript"> // 使用指令 angular.module("exampleApp",["triButtonDir"])

二、创建使用服务

1.使用Factory方法
第一步:将服务模块化,这里创建一个名为triButtonFactory.js的文件

angular.module("triButtonFactory",[])
    .factory("logService",function () {
        var messageCount = 0;
        return {
            log : function (msg) {
                console.log("(Log + " + messageCount++ + ") " + msg);
            }
        }
    })

第二步:在视图中引入该服务

<script type="text/javascript" src="js/triButtonFactory.js"></script>

第三步:在控制器中使用它

// 参数依赖注入
angular.module("exampleApp",["triButtonDirective","triButtonFactory"])
    // 作为参数传人控制器中
    .controller("defaultCtrl",function ($scope,logService) {
        // 数据模型
        $scope.data = {
            // 城市
            cities : ["London",// 点击总数
            totalClicks : 0
        };
        // 添加监听器,当点击总数发生变化时触发工厂函数
        $scope.$watch("data.totalClicks",function (newVal) {
            // console.log("Total click count: " + newVal);
            // 使用自定义服务
            logService.log("Total click count: " + newVal);
        }); 
    })

2.使用Service方法
第一步:创建构造函数,然后创建服务
我们命名为triButtonService.js

var baseLogger = function () {
    this.messageCount = 0;
    this.log = function (msg) {
        console.log(this.msgType + ": " + (this.messageCount++) + " " + msg);
    }
}

var debugLogger = function () {};
debugLogger.prototype = new baseLogger();
debugLogger.prototype.msgType = "Debug";


var errorLogger = function () {};
errorLogger.prototype = new baseLogger();
errorLogger.prototype.msgType = "Error";


angular.module("triButtonService",[])
    .service("logService",debugLogger)

第二步:引入triButtonService.js文件,然后使用服务

<!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> </head> <body ng-controller="defaultCtrl"> <div class="well"> <!-- 使用自定义指令 --> <div class="btn-group" tri-button counter="data.totalClicks"> <!-- 遍历按钮 --> <button class="btn btn-default" ng-repeat="city in data.cities"> {{city}} </button> </div> <h5>Total Clicks: {{data.totalClicks}}</h5> </div> <script type="text/javascript" src="js/angular.min.js"></script> <!-- 引入指令文件 --> <script type="text/javascript" src="js/triButtonDirective.js"></script> <script type="text/javascript" src="js/triButtonService.js"></script> <script type="text/javascript"> // 使用指令 angular.module("exampleApp","triButtonService"]) .controller("defaultCtrl",function ($scope,logService) { // 数据模型 $scope.data = { // 城市 cities : ["London",function (newVal) { // console.log("Total click count: " + newVal); // 使用自定义服务 logService.log("Total click count: " + newVal); }); }) </script> </body> </html>

3.使用Provider方法
第一步:使用Provider,创建服务
我们命名为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; } },// 用于返回服务对象 $get : function () { return { messageCount : 0,log : function (msg) { if (debug) { console.log("(LOG" + (counter ? " + " + this.messageCount++ + ") " : ") " + msg)); } } } } } })

第二步:引入、配置和使用服务

<!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> </head> <body ng-controller="defaultCtrl"> <div class="well"> <!-- 使用自定义指令 --> <div class="btn-group" tri-button counter="data.totalClicks"> <!-- 遍历按钮 --> <button class="btn btn-default" ng-repeat="city in data.cities"> {{city}} </button> </div> <h5>Total Clicks: {{data.totalClicks}}</h5> </div> <script type="text/javascript" src="js/angular.min.js"></script> <!-- 引入指令文件 --> <script type="text/javascript" src="js/triButtonDirective.js"></script> <script type="text/javascript" src="js/triButtonProvider.js"></script> <script type="text/javascript"> // 使用指令 angular.module("exampleApp","triButtonProvider"]) // 使提供强对象适用于依赖注入,服务器 + Provider = logServiceProvider .config(function (logServiceProvider) { logServiceProvider.debugEnabled(true).messageCounterEnabled(false); }) .controller("defaultCtrl",function (newVal) { // console.log("Total click count: " + newVal); // 使用自定义服务 logService.log("Total click count: " + newVal); }); }) </script> </body> </html>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读