zoukankan      html  css  js  c++  java
  • 42.angularJS自定义服务

    转自:https://www.cnblogs.com/best/tag/Angular/

    1.

    你可以创建自定义服务,链接到你的模块中:

     
     1 <!DOCTYPE html>
     2 <html>
     3 
     4 <head>
     5     <meta charset="utf-8">
     6     <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
     7 </head>
     8 
     9 <body>
    10     <div ng-app="myApp" ng-controller="myCtrl">
    11 
    12         <p>255 的16进制是:</p>
    13 
    14         <h1>{{hex}}</h1>
    15 
    16     </div>
    17 
    18     <p>自定义服务,用于转换16进制数:</p>
    19 
    20     <script>
    21             var app = angular.module('myApp',[]);
    22             app.service('hexafy',function(){
    23                 this.myFunc = function(x){
    24                     return x.toString(16);
    25                 }
    26             });
    27             app.controller('myCtrl',function($scope,hexafy){
    28                 $scope.hex = hexafy.myFunc(255);
    29             });
    30     </script>
    31 
    32 </body>
    33 
    34 </html>

    2.

    过滤器中,使用自定义服务

    当你创建了自定义服务,并连接到你的应用上后,你可以在控制器,指令,过滤器或其他服务中使用它。

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="utf-8">
     5 <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
     6 </head>
     7 <body>
     8 
     9 <div ng-app="myApp" ng-controller="myCtrl">
    10 <p>在获取数组 [255, 251, 200] 值时使用过滤器:</p>
    11 
    12 <ul>
    13   <li ng-repeat="x in counts">{{x | myFormat}}</li>
    14 </ul>
    15 
    16 <p>过滤器使用服务将10进制转换为16进制。</p>
    17 </div>
    18 
    19 <script>
    20 var app = angular.module('myApp', []);
    21 app.service('hexafy', function() {
    22     this.myFunc = function (x) {
    23         return x.toString(16);
    24     }
    25 });
    26 app.filter('myFormat',['hexafy', function(hexafy) {
    27     return function(x) {
    28         return hexafy.myFunc(x);
    29     };
    30 }]);
    31 app.controller('myCtrl', function($scope) {
    32     $scope.counts = [255, 251, 200];
    33 });
    34 </script>
    35 
    36 </body>
    37 </html>
  • 相关阅读:
    第二十一章 PHP编译安装(centos7)
    第二十章 nginx常见问题
    第十九章 keepalived高可用
    dijkstra
    求逆序对
    A
    P2014 [CTSC1997]选课
    樱花 混合背包
    1401D
    CF1343D
  • 原文地址:https://www.cnblogs.com/sharpest/p/8176873.html
Copyright © 2011-2022 走看看