AngularJs Service-自定义服务

前端之家收集整理的这篇文章主要介绍了AngularJs Service-自定义服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在AngularJs中 ,服务是一个函数或对象,可以在你的AngularJs 应用中使用

服务是注册在模块下的

实例1:

  1. <div ng-app="myApp" ng-controller="myCtrl">
  2. <p>
  3. 数字:{{number}}
  4. </p>
  5. <p>
  6. 十六进制:<b>{{number2}}</b>
  7. </p>
  8. <p>
  9. 十六进制2:<b>{{number|myFormat}}</b>
  10. </p>
  11. </div>
  12. <script>
  13. //在AngularJs中 ,服务是一个函数或对象,可以在你的AngularJs 应用中使用
  14. //在控制器、在过滤器等中都可以使用
  15. //AngularJS 内建了30 多个服务。
  16. //创建自定义服务
  17. var app = angular.module('myApp',[]);
  18. app.service('hexfay',function () {
  19. this.getHex = function (x) {
  20. return x.toString(16);
  21. }
  22. });
  23. //要是使用定义的服务,需要再定义控制器的时候独立添加
  24. app.value('number',10);
  25. app.controller('myCtrl',function ($scope,number,hexfay) {
  26. $scope.number = number;
  27. $scope.number2 = hexfay.getHex($scope.number);
  28. });
  29. //在过滤器中使用服务
  30. app.filter('myFormat',function (hexfay) {
  31. return function (input) {
  32. return hexfay.getHex(input);
  33. }
  34. });
  35. </script>


实例2:

  1. <div ng-app="myApp" ng-controller="myCtrl">
  2. <p>数字:{{number}}</p>
  3. <p>结果:<b>{{number2}}</b></p>
  4. </div>
  5. <script>
  6. //创建自定义服务1
  7. var app = angular.module('myApp',[]);
  8. app.service('addition',function () {
  9. this.add = function (x) {
  10. return x + 10;
  11. }
  12. });
  13. //创建自定义服务2,调用服务1
  14. app.service('multipli',function (addition) {
  15. this.getMulti = function (x) {
  16. x = addition.add(x);
  17. return x * 10;
  18. }
  19. });
  20. //要是使用定义的服务,需要再定义控制器的时候独立添加
  21. app.value('number',10);
  22. app.controller('myCtrl',multipli) {
  23. $scope.number = number;
  24. $scope.number2 = multipli.getMulti($scope.number);
  25. });
  26. </script>

猜你在找的Angularjs相关文章