Angular JS 学习之服务(Service)

1.AngularJS中,可以创建自己的服务,或使用内建服务;

2.在AngularJS中,服务是一个函数或对象,可在你的AngularJS应用中使用;

AngularJS内建了30多个服务;有个$location服务,它可以返回当前页面的URL;

var app=angular.module('myApp',[]);

app.controller('customersCtrl',function($scope,$location){

  $scope.myUrl=$location.absUrl();

});

3.$http是AngularJS应用中最常用的服务;服务向服务器发送请求,应用响应服务器传过来的数据;

AngularJS会一直监控应用,处理事件变化,AngularJS使用$location服务比使用window。location对象更好;

var app=angular('myApp',[]);

app.controller('myCtrl',function($scope,$http){

  $http.get("Welcome.htm").then(function(response){

    $scope.myWelcome=response.data;

  });

});

4.$timeout服务:响应了JS window.setTimeout函数:

var app=angular.module('myApp',[]);

app.controller('myCtrl',function($scope,$timeout){

  $scope.myHeader="Hello World!";

  $timeout(function(){

    $scope.myHeader="How are you today?";

  },2000);

});

5.$interval服务:对应了JS window.setInterval函数

var app=angular.module('myApp',[]);

app.controller('myCtrl',function($scope,$interval){

  $scope.theTime=new Date().toLocaleTimeString();

  $interval(function(){

    $scope.theTime=new Date().toLocaleTimeString();

  },1000);

});

6.创建自定义服务:可以创建访问自定义服务,链接到你的模块中;

app.service('hexafy',function(){

  this.myFunc=function(x){

    return x.toString(16);

  }

});

使用访问自定义服务,需要在定义过滤器的时候独立添加:

app.controller('myCtrl',function($scope,hexafy){

  $scope.hex=hexafy.myFunc(255);

});

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

在过滤器myFormat中使用服务hexafy:

app.filter('myFormat',['hexafy',function(hexafy){

  return function(x){

    return hexafy.myFunc(x);

  };

}]);

原文地址:https://www.cnblogs.com/hqutcy/p/6067442.html