1
AngularJS 进阶 (四十) 创建模块、服务
- 2022-12-16 上海
本文字数:4748 字
阅读完需:约 16 分钟

学习要点
使用模块构架应用
创建和使用服务
为什么要使用和创建服务与模块?
服务允许你打包可重用的功能,使之能在此应用中使用。
模块允许你打包可重用的功能,使之能跨应用使用。
一、应用程序模块化
先看看一个没有模块化的程序
<!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, element, 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"])复制代码
二、创建使用服务
2.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", "New York", "Paris"], // 点击总数 totalClicks : 0 }; // 添加监听器,当点击总数发生变化时触发工厂函数 $scope.$watch("data.totalClicks", function (newVal) { // console.log("Total click count: " + newVal); // 使用自定义服务 logService.log("Total click count: " + newVal); }); })复制代码
2.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", ["triButtonDirective", "triButtonService"]) .controller("defaultCtrl", function ($scope, logService) { // 数据模型 $scope.data = { // 城市 cities : ["London", "New York", "Paris"], // 点击总数 totalClicks : 0 }; // 添加监听器,当点击总数发生变化时触发工厂函数 $scope.$watch("data.totalClicks", function (newVal) { // console.log("Total click count: " + newVal); // 使用自定义服务 logService.log("Total click count: " + newVal); }); }) </script></body></html>复制代码
2.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", ["triButtonDirective", "triButtonProvider"]) // 使提供强对象适用于依赖注入,服务器 + Provider = logServiceProvider .config(function (logServiceProvider) { logServiceProvider.debugEnabled(true).messageCounterEnabled(false); }) .controller("defaultCtrl", function ($scope, logService) { // 数据模型 $scope.data = { // 城市 cities : ["London", "New York", "Paris"], // 点击总数 totalClicks : 0 }; // 添加监听器,当点击总数发生变化时触发工厂函数 $scope.$watch("data.totalClicks", function (newVal) { // console.log("Total click count: " + newVal); // 使用自定义服务 logService.log("Total click count: " + newVal); }); })</script></body></html>复制代码
划线
评论
复制
发布于: 刚刚阅读数: 5
版权声明: 本文为 InfoQ 作者【No Silver Bullet】的原创文章。
原文链接:【http://xie.infoq.cn/article/1c17db1e9d20d1dec110c2361】。文章转载请联系作者。
No Silver Bullet 2021-07-09 加入
岂曰无衣 与子同袍








评论