Skip to content

AngularJS angular.module, $scope, $http API

AngularJS (1.x) core APIs — module definition with controllers/services/directives, the $scope digest loop, and $http for XHR.

3 classes · 12 methods

module

4 methods

angular.module for defining an application module, plus its controller, service, and directive registration.

angular.module(name, requires?) -> module

Getter/setter for a module. With requires it creates a new module; without requires it retrieves an existing one.

Parameters

NameTypeDescription
namestringModule name.
requiresArrayArray of dependency module names (omit to get an existing module).

Returns

module

Example

angularjs
const app = angular.module('myApp', ['ngRoute']);
module.controller(name, constructor)

Registers a controller constructor on the module; inject dependencies by parameter name or $inject annotation.

Parameters

NameTypeDescription
namestringController name.
constructorFunctionConstructor function with injectable deps.

Returns

module

Example

angularjs
app.controller('UserCtrl', function ($scope, $http) {
  $scope.user = { name: 'Sam' };
});
module.service(name, constructor)

Registers a singleton service instantiated with new; inject dependencies via the constructor.

Parameters

NameTypeDescription
namestringService name.
constructorFunctionConstructor function.

Returns

module

Example

angularjs
app.service('UserService', function ($http) {
  this.list = () => $http.get('/api/users');
});
module.directive(name, factory)

Registers a directive with a factory function returning a Directive Definition Object (DDO).

Parameters

NameTypeDescription
namestringDirective name in camelCase.
factoryFunctionFactory returning a DDO with restrict, template, link, etc.

Returns

module

Example

angularjs
app.directive('hello', function () {
  return {
    restrict: 'E',
    template: '<h1>Hello, {{name}}!</h1>',
    scope: { name: '@' },
  };
});

$scope

4 methods

The $scope object — the glue between controllers and views — and its digest-cycle methods.

$scope.$watch(watchExpression, listener, deep?)

Registers a listener callback invoked whenever the watched expression changes during the digest cycle.

Parameters

NameTypeDescription
watchExpressionstring | FunctionExpression to watch.
listener(newValue, oldValue, scope) => voidCallback on change.
deepbooleanOptional; true for deep (object equality) watch.

Returns

Function (deregistration)

Example

angularjs
$scope.$watch('user.name', function (n, o) {
  console.log('name changed', o, '->', n);
}, true);
$scope.$apply(expr?)

Manually triggers the digest cycle, evaluating expr and propagating changes to watchers. Use when updating scope from non-AngularJS code.

Parameters

NameTypeDescription
exprstring | FunctionOptional expression to evaluate inside the digest.

Returns

any (result of expr)

Example

angularjs
setTimeout(function () {
  $scope.$apply(function () {
    $scope.count = 10;
  });
}, 1000);
$scope.$on(name, listener)

Listens for an event broadcast ($broadcast) or emitted ($emit) on the scope hierarchy.

Parameters

NameTypeDescription
namestringEvent name.
listener(event, ...args) => voidHandler called on event.

Returns

Function (deregistration)

Example

angularjs
$scope.$on('user:login', function (event, user) {
  console.log('logged in', user);
});
$scope.$broadcast(name, args...)

Dispatches an event downward to all child scopes (and their children).

Parameters

NameTypeDescription
namestringEvent name.
argsanyOptional arguments passed to listeners.

Returns

event

Example

angularjs
$scope.$broadcast('item:added', { id: 1 });

$http

4 methods

The $http service for making XMLHttpRequests. Methods return promises resolved with response data, status, and headers.

$http.get(url, config?) -> Promise

Performs an HTTP GET request. The returned promise resolves to a response object with data, status, headers, config.

Parameters

NameTypeDescription
urlstringRequest URL.
configobjectOptional { params, headers, cache, ... }.

Returns

HttpPromise

Example

angularjs
$http.get('/api/users/1').then(function (resp) {
  console.log(resp.data);
});
$http.post(url, data, config?) -> Promise

Performs an HTTP POST request with a request body serialized as JSON by default.

Parameters

NameTypeDescription
urlstringRequest URL.
dataanyRequest body.
configobjectOptional { headers, params, ... }.

Returns

HttpPromise

Example

angularjs
$http.post('/api/users', { name: 'Sam' })
  .then(function (resp) { console.log(resp.data); });
$http(config) -> Promise

Generic request method using a config object with method, url, data, params, headers.

Parameters

NameTypeDescription
configobject{ method, url, data, params, headers, ... }.

Returns

HttpPromise

Example

angularjs
$http({ method: 'PUT', url: '/api/users/1', data: { name: 'Sam2' } })
  .then(function (resp) { console.log(resp.status); });
promise.then(successCallback, errorCallback?) -> Promise

Registers callbacks for the response. The success callback receives the full response; the error callback receives the HTTP error.

Parameters

NameTypeDescription
successCallback(response) => anyCalled on 2xx response.
errorCallback(response) => anyCalled on non-2xx response.

Returns

Promise

Example

angularjs
$http.get('/api/users')
  .then(
    function (resp) { console.log('ok', resp.data); },
    function (resp) { console.error('err', resp.status); }
  );