AngularJS进阶(四十)创建模块、服务

举报
SHQ5785 发表于 2020/12/30 00:27:38 2020/12/30
【摘要】 AngularJS进阶(四十)创建模块、服务 学习要点      使用模块构架应用      创建和使用服务      为什么要使用和创建服务与模块?           服务允许你打包可重用的功能,使之能在此应用中使用。           模块允许你打包可重用的功能,使之能跨应用使用。 一、应用程序模块化      先看看一个没有模块化的程序   ...

AngularJS进阶(四十)创建模块、服务

学习要点

     使用模块构架应用

     创建和使用服务

     为什么要使用和创建服务与模块?

          服务允许你打包可重用的功能,使之能在此应用中使用。

          模块允许你打包可重用的功能,使之能跨应用使用。

一、应用程序模块化

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

 


  
  1. <!DOCTYPE>
  2. <!-- use module -->
  3. <html ng-app="exampleApp">
  4. <head>
  5. <title>Angluar test</title>
  6. <meta charset="utf-8"/>
  7. <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
  8. <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
  9. </head>
  10. <body ng-controller="defaultCtrl">
  11. <div class="well">
  12. <!-- 使用自定义指令 -->
  13. <div class="btn-group" tri-button counter="data.totalClicks">
  14. <!-- 遍历按钮 -->
  15. <button class="btn btn-default" ng-repeat="city in data.cities">
  16. {{city}}
  17. </button>
  18. </div>
  19. <h5>Total Clicks: {{data.totalClicks}}</h5>
  20. </div>
  21. <script type="text/javascript" src="js/angular.min.js"></script>
  22. <script type="text/javascript">
  23. angular.module("exampleApp", [])
  24. .controller("defaultCtrl", function ($scope) {
  25. // 数据模型
  26. $scope.data = {
  27. // 城市
  28. cities : ["London", "New York", "Paris"],
  29. // 点击总数
  30. totalClicks : 0
  31. };
  32. // 添加监听器,当点击总数发生变化时触发工厂函数
  33. $scope.$watch("data.totalClicks", function (newVal) {
  34. console.log("Total click count: " + newVal);
  35. });
  36. })
  37. // 定义指令
  38. .directive("triButton", function () {
  39. return {
  40. // 隔离作用域
  41. // 双向数据绑定
  42. scope : {
  43. counter : "=counter"
  44. },
  45. // 链式函数
  46. link : function (scope, element, attrs) {
  47. // 点击事件监听,打印日记,计算累加
  48. element.on("click", function (e) {
  49. console.log("Button click: " + e.target.innerText);
  50. scope.$apply(function () {
  51. scope.counter++;
  52. })
  53. });
  54. }
  55. }
  56. })
  57. </script>
  58. </body>
  59. </html>

 

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

 

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

 


  
  1. angular.module("triButtonDir", [])
  2. .directive("triButton", function () {
  3. return {
  4. // 隔离作用域
  5. // 双向数据绑定
  6. scope : {
  7. counter : "=counter"
  8. },
  9. // 链式函数
  10. link : function (scope, element, attrs) {
  11. // 点击事件监听,打印日记,计算累加
  12. element.on("click", function (e) {
  13. console.log("Button click: " + e.target.innerText);
  14. scope.$apply(function () {
  15. scope.counter++;
  16. })
  17. });
  18. }
  19. }
  20. })

 

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

 


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

 

二、创建使用服务

1.使用Factory方法

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

 


  
  1. angular.module("triButtonFactory", [])
  2. .factory("logService", function () {
  3. var messageCount = 0;
  4. return {
  5. log : function (msg) {
  6. console.log("(Log + " + messageCount++ + ") " + msg);
  7. }
  8. }
  9. })

 

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

 

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

 

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

 


  
  1. // 参数依赖注入
  2. angular.module("exampleApp", ["triButtonDirective", "triButtonFactory"])
  3. // 作为参数传人控制器中
  4. .controller("defaultCtrl", function ($scope, logService) {
  5. // 数据模型
  6. $scope.data = {
  7. // 城市
  8. cities : ["London", "New York", "Paris"],
  9. // 点击总数
  10. totalClicks : 0
  11. };
  12. // 添加监听器,当点击总数发生变化时触发工厂函数
  13. $scope.$watch("data.totalClicks", function (newVal) {
  14. // console.log("Total click count: " + newVal);
  15. // 使用自定义服务
  16. logService.log("Total click count: " + newVal);
  17. });
  18. })
<img data-cke-saved-src="https://img-blog.csdn.net/20160615210752345?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" src="https://img-blog.csdn.net/20160615210752345?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />


 

 

2.使用Service方法

     第一步:创建构造函数,然后创建服务。我们命名为triButtonService.js

 


  
  1. var baseLogger = function () {
  2. this.messageCount = 0;
  3. this.log = function (msg) {
  4. console.log(this.msgType + ": " + (this.messageCount++) + " " + msg);
  5. }
  6. }
  7. var debugLogger = function () {};
  8. debugLogger.prototype = new baseLogger();
  9. debugLogger.prototype.msgType = "Debug";
  10. var errorLogger = function () {};
  11. errorLogger.prototype = new baseLogger();
  12. errorLogger.prototype.msgType = "Error";
  13. angular.module("triButtonService", [])
  14. .service("logService", debugLogger)

 

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

 


  
  1. <!DOCTYPE>
  2. <!-- use module -->
  3. <html ng-app="exampleApp">
  4. <head>
  5. <title>Angluar test</title>
  6. <meta charset="utf-8"/>
  7. <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
  8. <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
  9. </head>
  10. <body ng-controller="defaultCtrl">
  11. <div class="well">
  12. <!-- 使用自定义指令 -->
  13. <div class="btn-group" tri-button counter="data.totalClicks">
  14. <!-- 遍历按钮 -->
  15. <button class="btn btn-default" ng-repeat="city in data.cities">
  16. {{city}}
  17. </button>
  18. </div>
  19. <h5>Total Clicks: {{data.totalClicks}}</h5>
  20. </div>
  21. <script type="text/javascript" src="js/angular.min.js"></script>
  22. <!-- 引入指令文件 -->
  23. <script type="text/javascript" src="js/triButtonDirective.js"></script>
  24. <script type="text/javascript" src="js/triButtonService.js"></script>
  25. <script type="text/javascript">
  26. // 使用指令
  27. angular.module("exampleApp", ["triButtonDirective", "triButtonService"])
  28. .controller("defaultCtrl", function ($scope, logService) {
  29. // 数据模型
  30. $scope.data = {
  31. // 城市
  32. cities : ["London", "New York", "Paris"],
  33. // 点击总数
  34. totalClicks : 0
  35. };
  36. // 添加监听器,当点击总数发生变化时触发工厂函数
  37. $scope.$watch("data.totalClicks", function (newVal) {
  38. // console.log("Total click count: " + newVal);
  39. // 使用自定义服务
  40. logService.log("Total click count: " + newVal);
  41. });
  42. })
  43. </script>
  44. </body>
  45. </html>
<img data-cke-saved-src="https://img-blog.csdn.net/20160615210907926?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" src="https://img-blog.csdn.net/20160615210907926?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />


 

 

3.使用Provider方法

     第一步:使用Provider,创建服务。我们命名为triButtonProvider.js

 


  
  1. angular.module("triButtonProvider", [])
  2. .provider("logService", function () {
  3. var counter = true;
  4. var debug = true;
  5. return {
  6. messageCounterEnabled : function (setting) {
  7. if (angular.isDefined(setting)) {
  8. counter = setting;
  9. return this;
  10. } else {
  11. return counter;
  12. }
  13. },
  14. debugEnabled : function (setting) {
  15. if (angular.isDefined(setting)) {
  16. debug = setting;
  17. return this;
  18. } else {
  19. return debug;
  20. }
  21. },
  22. // 用于返回服务对象
  23. $get : function () {
  24. return {
  25. messageCount : 0,
  26. log : function (msg) {
  27. if (debug) {
  28. console.log("(LOG" + (counter ? " + " + this.messageCount++ + ") " : ") " + msg));
  29. }
  30. }
  31. }
  32. }
  33. }
  34. })

 

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

 


  
  1. <!DOCTYPE>
  2. <!-- use module -->
  3. <html ng-app="exampleApp">
  4. <head>
  5. <title>Angluar test</title>
  6. <meta charset="utf-8"/>
  7. <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
  8. <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
  9. </head>
  10. <body ng-controller="defaultCtrl">
  11. <div class="well">
  12. <!-- 使用自定义指令 -->
  13. <div class="btn-group" tri-button counter="data.totalClicks">
  14. <!-- 遍历按钮 -->
  15. <button class="btn btn-default" ng-repeat="city in data.cities">
  16. {{city}}
  17. </button>
  18. </div>
  19. <h5>Total Clicks: {{data.totalClicks}}</h5>
  20. </div>
  21. <script type="text/javascript" src="js/angular.min.js"></script>
  22. <!-- 引入指令文件 -->
  23. <script type="text/javascript" src="js/triButtonDirective.js"></script>
  24. <script type="text/javascript" src="js/triButtonProvider.js"></script>
  25. <script type="text/javascript">
  26. // 使用指令
  27. angular.module("exampleApp", ["triButtonDirective", "triButtonProvider"])
  28. // 使提供强对象适用于依赖注入,服务器 + Provider = logServiceProvider
  29. .config(function (logServiceProvider) {
  30. logServiceProvider.debugEnabled(true).messageCounterEnabled(false);
  31. })
  32. .controller("defaultCtrl", function ($scope, logService) {
  33. // 数据模型
  34. $scope.data = {
  35. // 城市
  36. cities : ["London", "New York", "Paris"],
  37. // 点击总数
  38. totalClicks : 0
  39. };
  40. // 添加监听器,当点击总数发生变化时触发工厂函数
  41. $scope.$watch("data.totalClicks", function (newVal) {
  42. // console.log("Total click count: " + newVal);
  43. // 使用自定义服务
  44. logService.log("Total click count: " + newVal);
  45. });
  46. })
  47. </script>
  48. </body>
  49. </html>

美文美图

 

文章来源: shq5785.blog.csdn.net,作者:No Silver Bullet,版权归原作者所有,如需转载,请联系作者。

原文链接:shq5785.blog.csdn.net/article/details/51685320

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200