This is the multi-page printable view of this section. Click here to print.
Services
- 1: $compile
- 2: $controller
- 3: $eventBus
- 4: $http
- 5: $interpolate
- 6: $location
- 7: $log
- 8: $parse
- 9: $rootElement
- 10: $rootScope
- 11: $sce
- 12: $templateCache
- 13: $templateRequest
- 14: $url
1 - $compile
2 - $controller
3 - $eventBus
Description
A messaging service, backed by an instance of
PubSub. This implementation is based on
the original
Google Closure PubSub
but uses
Promise.resolve()
instead of
Window.setTimeout()
for its async implementation. $eventBus allows communication between an
Angular application instance and the outside context, which can be a different
module, a non-Angular application, a third-party party library, or even a WASM
application. Additionally, $eventBus can be used to communicate directly with
a template, using ng-channel directive.
$eventBus should not be used for communicating between Angular’s own
primitives.
- For sharing application state: use custom Services and Factories that encapsulate your business logic and manage your model.
- For intercomponent communication: use
$scope.$on(),$scope.$emit(), and$scope.$broadcast()methods.
The example below demonstrates communication between the global window context
and a controller. Note: Ensure topic clean-up after the $scope is
destroyed
Example
<section ng-app="demo">
<div ng-controller="DemoCtrl as $ctrl">
Milliseconds elapsed since the epoch <b>{{ $ctrl.ms }}</b>
</div>
</section>
<!--We are using a regular onclick and `angular` global -->
<button
class="btn btn-dark"
onclick="angular.$eventBus.publish('demo', Date.now())"
>
Publish time
</button>
window.angular.module('demo', []).controller(
'DemoCtrl',
class {
static $inject = ['$eventBus', '$scope'];
constructor($eventBus, $scope) {
const key = $eventBus.subscribe('demo', (val) => {
// `this.ms = val` will not work because `this` is not a proxy
// to trigger change detection, we access controller as a scope property
$scope.$ctrl.ms = val;
});
$scope.$on('$destroy', () => $eventBus.unsubscribeByKey(key));
}
},
);
Demo
For detailed method description, see PubSub
4 - $http
$http Service (AngularTS)
The $http service is a core AngularTS service that facilitates communication
with remote HTTP servers via the browser’s
XMLHttpRequest object or via
JSONP.
For unit testing applications that use the $http service, see
$httpBackend mock.
For a higher-level abstraction, see the
$resource
service.
The $http API is based on the
$q deferred/promise APIs.
Familiarity with these APIs is important for advanced usage.
General Usage
The $http service is a function that takes a single argument — a
configuration object — used to generate an HTTP request. It returns a
promise that resolves on success or rejects on failure with a response
object.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// Called asynchronously when the response is available
}, function errorCallback(response) {
// Called asynchronously if an error occurs or the server returns an error
});
Shortcut Methods
Shortcut methods are available for all common HTTP methods. All require a URL; POST/PUT requests require data. An optional config object can be passed as the last argument.
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Shortcut methods list:
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.patch
$http.get(...);
Setting HTTP Headers
The $http service automatically adds certain HTTP headers to all requests. These defaults can be configured using $httpProvider.defaults.headers.
Default headers:
Common headers: Accept: application/json, text/plain, */*
POST headers: Content-Type: application/json
PUT headers: Content-Type: application/json
You can modify defaults:
$httpProvider.defaults.headers.get = { 'My-Header': 'value' };
Or modify headers globally at runtime:
module.run(function($http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});
Per-request overrides:
let req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
};
$http(req).then(success, error);
Transforming Requests and Responses
Requests and responses can be transformed using transformRequest and transformResponse. Each can be a single function or an array of functions. Functions take (data, headersGetter[, status]) and return the transformed value.
Note: AngularTS does not make a copy of data before passing it to transformRequest. Avoid side effects.
Default transformations:
Requests: objects are serialized to JSON
Responses: XSRF prefix removed; JSON responses are parsed
Per-request override example:
function appendTransform(defaults, transform) {
defaults = angular.isArray(defaults) ? defaults : [defaults];
return defaults.concat(transform);
}
$http({
url: '...',
method: 'GET',
transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
return doTransform(value);
})
});
Caching
By default, $http responses are not cached. Enable caching with:
config.cache = true or a cache object
Global default cache: $http.defaults.cache = true
Only GET and JSONP requests are cached.
Interceptors
Interceptors allow modification of requests/responses globally. Add factories to $httpProvider.interceptors.
Interceptor types:
request(config)
requestError(rejection)
response(response)
responseError(rejection)
Example:
$provide.factory('myHttpInterceptor', function($q) {
return {
request: function(config) { return config; },
responseError: function(rejection) { return $q.reject(rejection); }
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
5 - $interpolate
6 - $location
Description
The $location service parses the URL in the browser address bar (based on the
window.location) and makes
the URL available to your application in a uniform manner. Changes to the URL in
the address bar are reflected into $location service and changes to
$location are reflected into the browser address bar. Using $location you
can:
- Watch and observe the URL
- Change the URL
- Detect users changes to address bar by clicking on links or using back or forward buttons in browser
To configure the HTML5 mode and link behavior for the service, use the
$locationProvider.
Events
$location#$locationChangeStart
- Description: Broadcast on root scope before a URL will change. This change
can be prevented by calling
preventDefaultmethod of the event. See Scope#$ons for more details about event object. Upon successful change$location#$locationChangeSuccessis fired.
The newState and oldState parameters may be defined only in HTML5 mode and
when the browser supports the HTML5 History API.
- Parameters: |
angularEvent|Object| No | Synthetic event object. | |newUrl|string| No | The new URL being navigated to. | |oldUrl|string| Yes | The URL prior to the change. | |newState|string| Yes | New history state object (HTML5 mode only). | |oldState|string| Yes | Previ
$location#$locationChangeSuccess
Description:
Broadcasted on the root scope after a URL was changed. The newState and
oldState parameters may be defined only in HTML5 mode and when the browser
supports the HTML5 History API.
Parameters
| angularEvent | Object | No | Synthetic event object. | | newUrl |
string | No | The new URL after change. | | oldUrl | string | Yes | The
previous URL before the change. | | newState | string | Yes | New history
state object (HTML5 mode only). | | oldState | string | Yes | Previous
history state object (HTML5 mode only). |
7 - $log
Using $log
Default implementation of LogService safely writes the message into the browser’s console (if present). The main purpose of this service is to simplify debugging and troubleshooting, while allowing the developer to modify the defaults for live environments.
Example*
angular.module('demo').controller('MyController', ($log) => {
$log.log('log');
$log.info('info');
$log.warn('warn!');
$log.error('error');
$log.debug('debug');
});
To reveal the location of the calls to $log in the JavaScript console, you can
“blackbox” the AngularTS source in your browser:
Note: Not all browsers support blackboxing.
The default is to logdebugmessages. You can use$logProvider.debugto change this.
For configuration and custom implementations, see $logProvider.
Decorating $log
You can also optionally override any of the $log service methods with
$provide decorator. Below is a simple example that overrides default
$log.error to log errors to both console and a backend endpoint.
Example*
angular.module('demo').config(($provide) => {
$provide.decorator('$log', ($delegate, $http, $exceptionHandler) => {
const originalError = $delegate.error;
$delegate.error = () => {
originalError.apply($delegate, arguments);
const errorMessage = Array.prototype.slice.call(arguments).join(' ');
$http.post('/api/log/error', { message: errorMessage });
};
return $delegate;
});
});
Overriding console
If your application is already heavily reliant on default
console logging or
you are using a third-party library where logging cannot be overriden, you can
still take advantage of Angular’s services by modifying the globals at runtime.
Below is an example that overrides default console.error to logs errors to
both console and a backend endpoint.
Example*
angular.module('demo').run(($http) => {
/**
* Decorate console.error to log error messages to the server.
*/
const $delegate = window.console.error;
window.console.error = (...args) => {
try {
const errorMessage = args
.map((arg) => (arg instanceof Error ? arg.stack : JSON.stringify(arg)))
.join(' ');
$delegate.apply(console, args);
$http.post('/api/log/error', { message: errorMessage });
} catch (e) {
console.warn(e);
}
};
/**
* Detect errors thrown outside Angular and report them to the server.
*/
window.addEventListener('error', (e) => {
window.console.error(e.error || e.message, e);
});
/**
* Optionally: Capture unhandled promise rejections
*/
window.addEventListener('unhandledrejection', (e) => {
window.console.error(e.reason || e);
});
});
Combining both $log decoration and console.log overriding provides a robust
and flexible error reporting strategy that can adapt to your use-case.
* array notation and HTTP error handling omitted for brevity
8 - $parse
9 - $rootElement
10 - $rootScope
11 - $sce
$sceProvider and $sce Documentation
$sceProvider
The $sceProvider provider allows developers to configure the $sce
service.
- Enable/disable Strict Contextual Escaping (SCE) in a module
- Override the default implementation with a custom delegate
Read more about Strict Contextual Escaping (SCE).
$sce
$sce is a service that provides Strict Contextual Escaping (SCE) services
to AngularTS.
Strict Contextual Escaping
Overview
Strict Contextual Escaping (SCE) is a mode in which AngularTS constrains bindings to only render trusted values. Its goal is to:
- Help you write secure-by-default code.
- Simplify auditing for vulnerabilities such as XSS and clickjacking.
By default, AngularTS treats all values as untrusted in HTML or sensitive URL bindings. When binding untrusted values, AngularTS will:
- Sanitize or validate them based on context.
- Or throw an error if it cannot guarantee safety.
Example — ng-bind-html renders its value directly as HTML (its “context”). If
the input is untrusted, AngularTS will sanitize or reject it.
To bypass sanitization, you must mark a value as trusted before binding it.
Note: Since version 1.2, AngularTS ships with SCE enabled by default.
Example: Binding in a Privileged Context
<input ng-model="userHtml" aria-label="User input" />
<div ng-bind-html="userHtml"></div>
If SCE is disabled, this allows arbitrary HTML injection — a serious XSS risk.
To safely render user content, you should sanitize the HTML (on the server or client) before binding it.
SCE ensures that only trusted, validated, or sanitized values are rendered.
You can mark trusted values explicitly using:
$sce.trustAs(context, value);
or shorthand methods such as:
$sce.trustAsHtml(value);
$sce.trustAsUrl(value);
$sce.trustAsResourceUrl(value);
How It Works
Directives and Angular internals bind trusted values using:
$sce.getTrusted(context, value);
Example: the ngBindHtml directive uses $sce.parseAsHtml internally:
let ngBindHtmlDirective = [
'$sce',
function ($sce) {
return function (scope, element, attr) {
scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function (value) {
element.html(value || '');
});
};
},
];
Impact on Loading Templates
SCE affects both:
- The
ng-includedirective - The
templateUrlproperty in directives
By default, AngularTS loads templates only from the same domain and protocol
as the main document.
It uses:
$sce.getTrustedResourceUrl(url);
To allow templates from other domains, use:
$sceDelegateProvider.trustedResourceUrlList- Or
$sce.trustAsResourceUrl(url)
Note: Browser CORS and Same-Origin policies still apply.
Is This Too Much Overhead?
SCE applies only to interpolation expressions.
Constant literals are automatically trusted, e.g.:
<div ng-bind-html="'<b>implicitly trusted</b>'"></div>
If the ngSanitize module is included, $sceDelegate will use $sanitize to
clean untrusted HTML automatically.
AngularTS’ default $sceDelegate allows loading from your app’s domain,
blocking others unless explicitly whitelisted.
This small overhead provides major security benefits and simplifies auditing.
Supported Trusted Contexts
| Context | Description |
|---|---|
$sce.HTML | Safe HTML (used by ng-bind-html). |
$sce.CSS | Safe CSS. Currently unused. |
$sce.MEDIA_URL | Safe media URLs (auto-sanitized). |
$sce.URL | Safe navigable URLs. |
$sce.RESOURCE_URL | Safe resource URLs (used in ng-include, iframe, etc.). |
$sce.JS | Safe JavaScript for execution. |
⚠️ Before AngularTS 1.7.0,
a[href]andimg[src]sanitized directly.
As of 1.7.0, these now use$sce.URLand$sce.MEDIA_URLrespectively.
Resource URL List Patterns
Trusted and banned resource URL lists accept:
'self'→ matches same domain & protocol- Strings with wildcards:
*→ matches within a single path segment**→ matches across path segments (use carefully)
- Regular expressions (
RegExp)
Caution: Regex patterns are powerful but harder to maintain — use only when necessary.
Disabling SCE (Not Recommended)
You can disable SCE globally — though this is strongly discouraged.
angular.module('myAppWithSceDisabled', []).config(function ($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects or libraries.
$sceProvider.enabled(false);
});
12 - $templateCache
$templateCache is a
Map
object created by $templateCacheProvider.
The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag by using $templateRequest or by consuming the $templateCache service directly.
Adding via the script tag:
Example
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
Note: the script tag containing the template does not need to be included in the
head of the document, but it must be a descendent of the $rootElement (e.g.
element with ng-app attribute), otherwise the template will be ignored.
Adding via the $templateCache service:
Example
const myApp = angular.module('myApp', []).run(($templateCache) => {
$templateCache.set('templateId.html', 'This is the content of the template');
});
To retrieve the template, simply use it in your component:
myApp.component('myComponent', {
templateUrl: 'templateId.html',
});
or include it with ng-include:
<div ng-include="'templateId.html`"></div>
or get it via the $templateCache service:
myApp.controller(
'Test',
class {
constructor($templateCache) {
const tmp = $templateCache.get('templateId.html');
}
},
);