码迷,mamicode.com
首页 > Web开发 > 详细

Angular JS 学习之服务(Service)

时间:2016-11-15 22:49:25      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:filter   interval   定义   nbsp   使用   win   src   log   header   

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);

  };

}]);

 

Angular JS 学习之服务(Service)

标签:filter   interval   定义   nbsp   使用   win   src   log   header   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!