• angularjs学习笔记--服务



    在angularjs中,服务是一个函数或对象,可在angularjs应用中使用。其中$location服务可以返回当前页面的url地址。要使用它,需要在controller中进行定义,作为一个参数传入到controller中。

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <script src="../angular/angular.js"></script>
    </head>
    <body>
    <p ng-app="myApp" ng-controller="customersCtrl">
    {{myUrl}}
    </p>
    <script>
    var app = angular.module('myApp',[]);
    app.controller('customersCtrl',function($scope,$location){
    $scope.myUrl = $location.absUrl();
    });
    </script>
    </body>
    </html>
    

      

    $http服务向服务器发送请求,应用响应服务器传送过来的数据。

    var app = angular.module("myApp",[]);
    app.controller("myCtrl",function($scope,$http){
    $http.get("welcome.html").then(function(response){
    $scope.myWelcome = response.data;
    });
    });
    

      

    $timeout

    var app = angular.module("myApp",[]);
    app.controller("myCtrl",function($scope,$timeout){
    $scope.myHeader = "hello world";
    $timeout(function(){
    $scope.myHeader = "how are you today?";
    },2000);
    });
    

      

    创建自定义服务:可以创建自定义服务,并链接到自己的模块中,但在访问自定义服务时,需要在定义控制器的时候独立添加,设置依赖关系。当自定义服务连接到自己的应用上后,可以在控制器/指令/过滤器或其他服务中使用它。

    app.service('hexafy',function(){
    this.myFunc = function(x){
    return x.toString(16);
    }
    });
    
    app.controller('myCtrl',function($scope,hexafy){
    $scope.hex = hexafy.myFunc(255);
    });
    
    app.filter('myFormat',['hexafy',function(hexafy){
    return function(x){
    return hexafy.myFunc(x);
    };
    }]);
    

      

    未完待续。。。

    宝剑锋从磨砺出,梅花香自苦寒来。
  • 相关阅读:
    黑域,黑阈 Permission denied
    手机闪存速度测试工具,AndroBench
    找进程的窗口Handle
    nginx http 正向代理
    windows命令行netstat 统计连接数
    FLIR ONE PRO热成像仪
    python2.0_s12_day14_jQuery详解
    python2.0_s12_day13_javascript&Dom&jQuery
    ssh&scp指定密钥
    apache+php生产环境错误记录
  • 原文地址:https://www.cnblogs.com/haimengqingyuan/p/7442079.html
Copyright © 2020-2023  润新知