为什么使用服务?
- 通过服务,AngularJS 会一直监控数据变化,否则就要依赖$watch和$apply
- 服务应当和$scope一起写在需引用处的function形参中
$http发起ajax请求(v1.5以下采用success和error代替then)
var app = angular.module('myApp', []);
app.controller('siteCtrl', function($scope, $http) {
$http({
method: 'GET',
url: 'https://www.runoob.com/try/angularjs/data/sites.php'
}).then(function successCallback(response) {
$scope.names = response.data.sites;
}, function errorCallback(response) {
// 请求失败执行代码
});
});
或简写为:
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
$apply和$watch
- $apply 手动触发更新数据
- 用$apply和setInterval模拟$Interval:
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
$scope.setTime = function() {
$scope.$apply(function() {
$scope.theTime = new Date().toLocaleTimeString();
});
};
setInterval($scope.setTime, 1000);
- $watch 监听lastName的变化,更新fullName
$scope.$watch('lastName', function() {
$scope.fullName = $scope.lastName + " " + $scope.firstName;
});
创建自定义服务
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
- 控制器中使用自定义服务
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
- 过滤器中使用自定义服务
<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>
app.filter('myFormat',['hexafy', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
}]);