14 内置服务1

内置服务1

在Angular里面,services作为单例对象在需要到的时候被创建,只有在应用生命周期结束的时候(关闭浏览器)才会被清除。而controllers在不需要的时候就会被销毁了。

Angular部分内置服务概览

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

名称 描述
$window 封装window对象。
$document 对浏览器对象window.document的jqLite封装,主要操作DOM.$document 等效于 angular.element(document),不过要注意两者的引用并不相等,并且,取0下标可以得到原生的document对象:$document[0] === document,即引用相等,因为是对浏览器的document对象的封装
$log 简单的打印日志的服务。默认实现安全的写入信息到浏览器的控制台(如果存在的话)。
$interval window.setInterval的Angular包装形式。
$timeout window.setTimeout的Angular包装形式
$rootScope 应用的根作用域
$http $http是Angular的一个核心服务,它有利于浏览器通过XMLHttpRequest 对象或者 JSONP和远程HTTP服务器交互。
$location $location服务解析浏览器地址中的url(基于window.location)并且使url在应用程序中可用。将地址栏中的网址的变化反映到$location服务和$location的变化反映到浏览器地址栏。
$anchorScroll 根据HTML5的规则,当调用这个函数时,它检查当前的url的hash值并且滚动到相应的元素。
$q 一个帮助处理异步执行函数的服务。当他们做完处理时,使用它们的返回值(或异常)。
$compile 编译一段HTML字符串或者DOM的模板, 产生一个将scope和模板连接到一起的函数。
$interpolate 将一个字符串编译成一个插值函数。HTML编译服务使用这个服务完成数据绑定。
$parse 将Angular表达式转换为函数。
$templateRequest $templateRequest服务运行进行安全检测,然后使用$http下载被提供的模板,成功后,将内容存储在$templateCache里。如果HTTP请求失败或HTTP请求的响应数据是空的,将抛出个$compile错误(通过设置该函数的第二个参数为true)。该注意的是,$templateCache的内容是可信的,所以调用$sce.getTrustedUrl(tpl)是省略的,当tpl的类型是字符串并且$templateCache具有匹配的项。
$templateCache 第一次使用模板,它被加载到模板缓存中,以便快速检索。你可以直接将模板标签加载到缓存中,或者通过$templateCache服务。
$sce $sce 服务是AngularJs提供的一种严格上下文转义服务。
$sceDelegate $sceDelegate是一个AngularJs为$sce服务提供严格的上下文转义服务的服务。
$animate $animate服务提供了基本的DOM操作功能如在DOM里插入、移除和移动元素,以及添加和删除类。这个服务是ngAnimate的核心服务,为CSS和Javascript提供了高档次的动画。

$log

$log服务很简单,就是更高级的console.log罢了,它提供5个方法:log、warn、info、error、debug

<div ng-controller="LogController">
<p>Reload this page with open console, enter text and hit the log button...</p>
<label>Message:
<input type="text" ng-model="message"/>
</label>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
<button ng-click="$log.debug(message)">debug</button>
</div>
angular.module('myDemo', [])
.controller('LogController', function ($scope, $log) {
$scope.$log = $log;
});

效果(浏览器F12打开控制台):

这里写图片描述

$timeout和$interval

$timeout(fn, [delay], [invokeApply],[Pass]);

$interval(fn, delay, [count], [invokeApply], [Pass]);

参数 类型 描述
fn function()= 一个将被延迟执行的函数。
delay num 延迟的时间(毫秒)。
count num 重复次数
invokeApply(可选) boolean 如果设置为false,则跳过脏值检测,否则将调用$apply。
Pass(可选) * 执行的函数的附加参数。
$timeout(function() {
$scope.myHeader = "How are you today?";
}, 2000);
$interval(function() {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);

$timeout$interval是AngularJS自带的服务,跟原生js中的setTimeoutsetInterval函数的用法基本是一样的。但是有两个不一样的地方需要注意一下:

  • 区别一:

原生js中的两个函数,如果在AngularJS中使用并且在回调函数中需要使用$scope服务的话,我们需要用$angular.$apply把回调函数包起来,因为这里setTimeout函数被AngularJS当作是外部函数了。就像这样:

// 错误的写法示例(使用setTimeout却没有用$apply):
angular.module('myDemo', [])
.controller('firstController', ['$scope', function ($scope) {
setTimeout(function () {
console.log('before'); // 正常输出before
$scope.name = "My name have been changed."; // 这一句不被执行
console.log('after'); // 正常输出after
}, 2000);
}]);
// 正确的写法示例
setTimeout(function () {
console.log('before'); // 正常输出before
$scope.$apply(function () {
$scope.name = "My name have been changed."; // 正确显示
});
console.log('after'); // 正常输出after
}, 2000);

所以,在AngularJS中,最好不要用setTimeout或setInterval,而是用那两个AngularJS系统服务。

  • 区别二:取消的方式不大一样,比如timeout:
// setTimeout
var id = setTimeout(func, 2000); // 返回该timeout的id
clearTimeout(id); // 使用clearTimeout

// $timeout服务
var promise = $timeout(f, 2000); // 返回一个promise对象
$timeout.cancel(promise); // 还是要使用服务,它的cancel方法,返回boolean

$cacheFactory和$cacheFactory.Cache

$cacheFactory是应用程序一个会话(Session)中的缓存服务,以key-value对的方法存储一些临时数据。它跟浏览器本地缓存localStorage是不一样的。$cacheFactory在用户删除当前会话(比如强制刷新页面)之后,缓存的数据就被清空了。

$cacheFactory.Cache:一个用于存储和检索数据的缓存对象。主要使用$http和脚本指令来缓存模板和其他数据。

要得到一个缓存实例,用id来区分,比如我想取id为’firstCache’的缓存:

var cache = $cacheFactory('firstCache');

方法 描述
put(key,value); 在缓存对象中插入一个键值对(key,value)。
key:string类型,缓存对象中的值名称。
value:所有类型,缓存对象中的值。
get(key); 在缓存对象中通过指定key获取对应的值。如果不存在这个key的话,会返回undefined
remove(key); 在缓存对象中通过指定key删除对应的值。
removeAll(); 删除缓存对象中所有的键值对。
destroy(); 销毁这个缓存对象。
info(); 获取缓存对象信息(id,size)。
(function () {
angular.module("Demo", [])
.controller("testCtrl", ["$cacheFactory",testCtrl]);
function testCtrl($cacheFactory) {
var myCache = $cacheFactory("my-cache");
myCache.put("cache", "This is cache-content");
myCache.put("another-cache", "This is another cache-content");
var getCache = myCache.get("cache"); //This is cache-content
var getInfo = myCache.info();//{id: "my-cache", size: 2}
myCache.remove("another-cache");
getInfo = myCache.info();//{id: "my-cache", size: 1}
myCache.removeAll();
getInfo = myCache.info();//{id: "my-cache", size: 0}
myCache.destroy();
getInfo = myCache.info();//{size: 0}
};
}());

猜你喜欢

转载自blog.csdn.net/Fighting_No1/article/details/80036430