Built-in service 1
In Angular, services are created as singleton objects when they are needed, and are only cleared when the application life cycle ends (closes the browser). And controllers are destroyed when they are not needed.
Overview of some built-in services in Angular
In AngularJS, a service is a function or object that can be used in your AngularJS application.
name | describe |
---|---|
$window |
Encapsulates the window object. |
$document |
window.document The jqLite encapsulation of the browser object mainly operates on the DOM. It $document is equivalent to angular.element(document) , but it should be noted that the references of the two are not equal, and the original document object can be obtained by taking the 0 subscript: $document[0] === document , that is, the reference is equal, because it is a reference to the browser The encapsulation of the document object |
$log |
Simple service for printing logs. The default implementation is to safely write information to the browser's console (if it exists). |
$interval |
window.setInterval Angular wrapper form. |
$timeout |
window.setTimeout Angular wrapper form |
$rootScope |
the root scope of the application |
$http |
$http Is a core service of Angular, which facilitates the browser to interact with the remote HTTP server through the XMLHttpRequest object or JSONP. |
$location |
$location The service resolves the url (based on) the browser address window.location and makes the url available in the application. Reflect changes to the URL in the address bar to the $location service and $location changes to the browser address bar. |
$anchorScroll |
According to HTML5 rules, when this function is called, it checks the hash of the current url and scrolls to the corresponding element. |
$q |
A service to help handle asynchronously executing functions. When they're done processing, use their return value (or exception). |
$compile |
Compiles an HTML string or DOM template, yielding a function that links the scope and template together. |
$interpolate |
Compile a string into an interpolation function. The HTML Compilation Service uses this service to perform data binding. |
$parse |
Convert Angular expressions to functions. |
$templateRequest |
$templateRequest The service runs for security detection, and then uses $http the provided template to download, and after success, stores the content in $templateCache it. If the HTTP request fails or the response data of the HTTP request is empty, an $compile error will be thrown (by setting the second parameter of this function to true). The note is that $templateCache the content of , is trusted, so the call $sce.getTrustedUrl(tpl) is omitted when tpl is of type string and $templateCache has a matching item. |
$templateCache |
The first time a template is used, it is loaded into the template cache for fast retrieval. You can load template tags directly into the cache, or through a $templateCache service. |
$sce |
$sce Service is a strict context escape service provided by AngularJs. |
$sceDelegate |
$sceDelegate is an AngularJs service that provides strict context escaping services for the $sce service. |
$animate |
$animate Services provide basic DOM manipulation functionality such as inserting, removing, and moving elements in the DOM, as well as adding and removing classes. This service is the core service of ngAnimate and provides high-level animations for CSS and Javascript. |
$log
$log
The service is very simple, it is more advanced console.log
, it provides 5 methods: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;
});
Effect (browser F12 to open the console):
$ timeout and $interval
$timeout(fn, [delay], [invokeApply],[Pass]);
$interval(fn, delay, [count], [invokeApply], [Pass]);
parameter | Types of | describe |
---|---|---|
fn | function()= |
A function that will be deferred. |
delay | num |
Delay time in milliseconds. |
count | num |
repeat times |
invokeApply (optional) | boolean |
If set to false, dirty value detection is skipped, otherwise $apply will be called. |
Pass (optional) | * |
Additional arguments to the executed function. |
$timeout(function() {
$scope.myHeader = "How are you today?";
}, 2000);
$interval(function() {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
$timeout
And is a service that comes with AngularJS, and the usage of the and function in $interval
native js is basically the same. But there are two differences to note:setTimeout
setInterval
- Difference one:
原生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}
};
}());