This is the multi-page printable view of this section. Click here to print.
Providers
- 1: $anchorScrollProvider
- 2: $animateProvider
- 3: $ariaProvider
- 4: $compileProvider
- 5: $cookieProvider
- 6: $eventBusProvider
- 7: $exceptionHandlerProvider
- 8: $httpProvider
- 9: $interpolateProvider
- 10: $locationProvider
- 11: $logProvider
- 12: $rootScopeProvider
- 13: $sceDelegateProvider
- 14: $sceProvider
- 15: $templateCacheProvider
- 16: $templateRequestProvider
1 - $anchorScrollProvider
$anchorScrollProvider controls whether $anchorScroll reacts automatically
when $location changes the URL hash.
Exact signatures live in TypeDoc:
Disable Automatic Scrolling
angular.module("demo", []).config(($anchorScrollProvider) => {
$anchorScrollProvider.autoScrollingEnabled = false;
});
Disable automatic scrolling when the application needs to coordinate hash changes with custom routing, animation, or focus management.
For service usage, see $anchorScroll.
2 - $animateProvider
Use $animateProvider during module configuration to limit which elements
animate and to register JavaScript animation factories.
Filtering Animations
Class-name filtering is useful when you want animation support only for specific parts of the DOM.
angular.module('app', []).config(($animateProvider) => {
$animateProvider.classNameFilter(/ng-animate/);
});
JavaScript Animation Factories
Register a factory for a CSS selector when CSS transitions are not enough.
angular.module('app', []).config(($animateProvider) => {
$animateProvider.register('.fade-card', () => ({
enter(element, done) {
element.animate([{ opacity: 0 }, { opacity: 1 }], 150).finished.then(done);
},
}));
});
See also Animation Directives.
3 - $ariaProvider
Use $ariaProvider to choose which accessibility attributes AngularTS manages
for common directives such as ng-show, ng-hide, ng-model, and disabled
controls.
angular.module('app', []).config(($ariaProvider) => {
$ariaProvider.config({
ariaHidden: true,
ariaChecked: true,
ariaDisabled: true,
ariaRequired: true,
ariaReadonly: true,
ariaValue: true,
tabindex: true,
});
});
See also ng-aria.
4 - $compileProvider
Use $compileProvider during module configuration for compiler-level behavior:
registering directives and controlling debug metadata.
Registering Directives
angular.module('app', []).config(($compileProvider) => {
$compileProvider.directive('focusOn', () => ({
restrict: 'A',
link(scope, element) {
element.focus();
},
}));
});
Debug Metadata
Disable debug metadata in production when you do not need scope lookup from DOM nodes.
angular.module('app', []).config(($compileProvider) => {
$compileProvider.debugInfoEnabled(false);
});
5 - $cookieProvider
$cookieProvider configures defaults that are merged into every $cookie.put(),
$cookie.putObject(), and $cookie.remove() call.
Exact signatures live in TypeDoc:
Set Defaults
angular.module("demo", []).config(($cookieProvider) => {
$cookieProvider.defaults = {
path: "/",
secure: true,
samesite: "Lax",
};
});
Use provider defaults for application-wide settings such as cookie path, HTTPS-only behavior, and SameSite policy. Per-call options still override these defaults.
For service usage, see $cookie.
6 - $eventBusProvider
$eventBusProvider creates the injectable $eventBus singleton and exposes the
same instance through the global Angular service for integrations outside
dependency injection.
Exact signatures live in TypeDoc:
Replace The Bus
angular.module("demo", []).config(($eventBusProvider) => {
$eventBusProvider.eventBus = new MyCustomPubSub();
});
Most applications should use the default PubSub instance. Replace it only when
you need custom dispatch, instrumentation, or compatibility with another event
system.
For service usage, see $eventBus.
7 - $exceptionHandlerProvider
$exceptionHandlerProvider configures the function used by $exceptionHandler.
The default handler rethrows the exception, and custom handlers should preserve
that behavior after reporting the error.
Exact signatures live in TypeDoc:
Configure Error Reporting
angular.module("demo", []).config(($exceptionHandlerProvider) => {
$exceptionHandlerProvider.handler = (error) => {
myLogger.capture(error);
throw error;
};
});
Rethrowing matters because the framework assumes $exceptionHandler does not
silently swallow fatal errors.
For service usage, see $exceptionHandler.
8 - $httpProvider
Use $httpProvider during module configuration to set application-wide HTTP
behavior before any request is made.
Exact provider members are documented in TypeDoc:
Defaults
Use defaults for headers, credentials, transforms, XSRF names, caching, and parameter serialization.
angular.module('app', []).config(($httpProvider) => {
$httpProvider.defaults.headers.common.Authorization = 'Bearer token';
$httpProvider.defaults.withCredentials = true;
});
Interceptors
Register interceptors to add cross-cutting request and response behavior.
angular.module('app', []).config(($httpProvider) => {
$httpProvider.interceptors.push(() => ({
request(config) {
config.headers['X-Timestamp'] = Date.now();
return config;
},
}));
});
XSRF
Add trusted origins before AngularTS sends XSRF headers to cross-origin APIs.
angular.module('app', []).config(($httpProvider) => {
$httpProvider.xsrfTrustedOrigins.push('https://api.example.com');
});
See also $http.
9 - $interpolateProvider
Use $interpolateProvider when AngularTS interpolation conflicts with a
server-side template language that also uses {{ }}.
angular.module('app', []).config(($interpolateProvider) => {
$interpolateProvider.startSymbol = '[[';
$interpolateProvider.endSymbol = ']]';
});
See also Templates and interpolation.
10 - $locationProvider
Use $locationProvider during module configuration to choose how AngularTS reads
and writes browser URLs.
Exact provider members are documented in TypeDoc:
HTML5 Mode
HTML5 mode uses the History API for clean URLs. Server routing must return the application shell for deep links.
angular.module('app', []).config(($locationProvider) => {
$locationProvider.html5ModeConf = {
enabled: true,
requireBase: false,
rewriteLinks: true,
};
});
Hash Prefix
Hash mode keeps application state after the # fragment. Configure the prefix
when you need hashbang-style URLs or compatibility with existing links.
angular.module('app', []).config(($locationProvider) => {
$locationProvider.hashPrefixConf = '!';
});
See also $location.
11 - $logProvider
Use $logProvider during module configuration to enable debug logging or
replace the logger implementation.
Exact provider members are documented in TypeDoc:
Debug Logging
angular.module('app', []).config(($logProvider) => {
$logProvider.debug = true;
});
Custom Logger
angular.module('app', []).config(($logProvider) => {
$logProvider.setLogger(() => ({
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
debug: console.debug,
}));
});
See also $log.
12 - $rootScopeProvider
Use $rootScopeProvider for application-wide scope configuration before the root
scope service is created.
Exact provider members are documented in TypeDoc:
Digest Iteration Limit
The digest TTL prevents infinite watch loops. Increase it only when you have a known, intentional chain of watchers that requires more iterations.
angular.module('app', []).config(($rootScopeProvider) => {
$rootScopeProvider.digestTtl(15);
});
See also $rootScope.
13 - $sceDelegateProvider
Use $sceDelegateProvider to control which resource URLs AngularTS may load for
contexts such as templates, includes, iframes, and other resource fetches. It
also owns the URL allowlists used when sanitizing bound link and media URLs.
Exact provider members are documented in TypeDoc:
Trusted Resource URLs
Allow same-origin resources with self, exact strings, wildcard strings, or
regular expressions.
angular.module('app', []).config(($sceDelegateProvider) => {
$sceDelegateProvider.trustedResourceUrlList([
'self',
'https://cdn.example.com/**',
]);
});
Banned Resource URLs
Banned patterns override trusted patterns. Use them to block a narrower path inside a broader trusted origin.
angular.module('app', []).config(($sceDelegateProvider) => {
$sceDelegateProvider.bannedResourceUrlList([
'https://cdn.example.com/private/**',
]);
});
URL Sanitization
Configure trusted URL patterns for links and media sources before templates are compiled.
angular.module('app', []).config(($sceDelegateProvider) => {
$sceDelegateProvider.aHrefSanitizationTrustedUrlList(/^https?:/);
$sceDelegateProvider.imgSrcSanitizationTrustedUrlList(
/^\s*((https?|file|blob):|data:image\/)/,
);
});
See also $sce.
14 - $sceProvider
$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);
});
15 - $templateCacheProvider
$templateCacheProvider initializes the cache used by $templateCache. The
default cache is a Map, but applications can provide another implementation
that satisfies the TemplateCache contract.
Exact signatures live in TypeDoc:
Use A Custom Cache
class LocalStorageTemplateCache {
constructor(prefix = "tpl:") {
this.prefix = prefix;
}
key(name) {
return `${this.prefix}${name}`;
}
get(name) {
const value = localStorage.getItem(this.key(name));
return value === null ? undefined : value;
}
set(name, value) {
localStorage.setItem(this.key(name), value);
return this;
}
has(name) {
return localStorage.getItem(this.key(name)) !== null;
}
delete(name) {
localStorage.removeItem(this.key(name));
return true;
}
clear() {
Object.keys(localStorage)
.filter((key) => key.startsWith(this.prefix))
.forEach((key) => localStorage.removeItem(key));
}
}
angular.module("demo", []).config(($templateCacheProvider) => {
$templateCacheProvider.cache = new LocalStorageTemplateCache();
});
Custom caches are useful when templates should survive reloads, be shared across tabs, or be backed by another browser storage layer.
For service usage, see $templateCache.