filter
内置的Service
自己的Service:
<!DOCTYPE html>
<html lang="en" ng-app="MyModule">
<head>
<meta charset="UTF-8">
<title>Service</title>
<link rel="stylesheet" href="static/asset/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div ng-controller="ServiceController">
<label>用户名</label>
<input type="text" ng-model="username" placeholder="请输入用户名" />
<pre ng-show="username">{{users}}</pre>
</div>
</body>
<script src="static/asset/angular-1.5.11/angular.js"></script>
<script src="static/compoments/service/service.js"></script>
</html>
angular.module('MyModule',[])
.factory('userListService',['$http',
function ($http) {
var doRequest = function (username, path) {
return $http({
method:'GET',
url:'user.json'
});
}
return{
userList:function (username) {
return doRequest(username,'userList');
}
}
}
])
.controller('ServiceController',['$scope','$timeout','userListService',
function ($scope,$timeout,userListService) {
var timeout;
$scope.$watch('username',function (newUserName) {
if(newUserName){
if(timeout){
$timeout.cancel(timeout);
}
timeout = $timeout(function () {
userListService.userList(newUserName)
.success(function (data,status) {
$scope.users = data;
})
},350)
}
})
}
])
这里的factory 可以返回一个带有属性和方法的对象。
Service的特性: Service都是单例。 Service由?injector负责实例化,就是说不用去new一个service。 Service在整个应用的生命周期中存在你,可以用来共享数据。 在需要使用的地方利用依赖机制注入Service。 自定义的Service需要写在内置的Service后面。 内置Service的命名以$符号开头,自定义Service应该避免。
Service,Provider,Factory: Service,Provider,Factory本质上都是Provider。 Provider模式是‘策略模式’+‘抽象工厂模式’的混合体。
filter: $filter是用来进行数据格式化的专用服务 AngularJS内置了9个filter: currency,date,json,limitTo,lowercase,number,orderBy,uppercase filter可以嵌套使用(用管道符号|分割) filter是可以传递参数的 用户可以定义自己的filter
常用的date filter:
<!DOCTYPE html>
<html lang="en" ng-app="MyModule">
<head>
<meta charset="UTF-8">
<title>Date</title>
</head>
<body>
{{ 1304375948024| date }}
<br>
{{ 1304375948024| date:"MM/dd/yyyy @h:mma" }}
<br>
{{ 1304375948024| date:"yyyy-MM-dd hh:mm:ss"}}
</body>
<script src="static/asset/angular-1.5.11/angular.js"></script>
<script src="static/compoments/date/date.js"></script>
</html>

自定义一个filter:
<!DOCTYPE html>
<html lang="en" ng-app="MyModule">
<head>
<meta charset="UTF-8">
<title>Filter</title>
</head>
<body>
{{'东方海外'|filter1}}
</body>
<script src="static/asset/angular-1.5.11/angular.js"></script>
<script src="static/compoments/filter/filter.js"></script>
</html>
angular.module('MyModule',[])
.filter('filter1',function () {
return function (item) {
return item+'OvO';
}
})

其他常用的Service: $compile filter interval 间歇性处理一些事情, locale 国际化 timeout location 观测地址栏的一些变化 log parse http 封装了Ajax