View source Improve this doc

ngController
directive in module ng

Description

The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.

MVC components in angular:

  • Model — The Model is scope properties; scopes are attached to the DOM where scope properties are accessed through bindings.
  • View — The template (HTML with data bindings) that is rendered into the View.
  • Controller — The ngController directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values

Note that you can also attach controllers to the DOM by declaring it in a route definition via the $route service. A common mistake is to declare the controller again using ng-controller in the template itself. This will cause the controller to be attached and executed twice.

Usage

as attribute
<ANY ng-controller="{expression}">
   ...
</ANY>

Directive info

  • This directive creates new scope.

Parameters

ParamTypeDetails
ngControllerexpression

Name of a globally accessible constructor function or an expression that on the current scope evaluates to a constructor function. The controller instance can be published into a scope property by specifying as propertyName.

Example

Here is a simple form for editing user contact information. Adding, removing, clearing, and greeting are methods declared on the controller (see source tab). These methods can easily be called from the angular markup. Notice that the scope becomes the this for the controller's instance. This allows for easy access to the view data from the controller. Also notice that any changes to the data are automatically reflected in the View without the need for a manual update. The example is shown in two different declaration styles you may use according to preference.

Source







Demo

Source







Demo