首页 > Web开发 > 详细

angularjs学习笔记--服务

时间:2017-08-28 09:22:14      阅读:294      评论:0      收藏:0      [点我收藏+]


在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);
};
}]);

  

未完待续。。。

 

angularjs学习笔记--服务

原文:http://www.cnblogs.com/haimengqingyuan/p/7442079.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!