AngularJS Controllers

AngularJS Controllers are where the most magic happens. Think that the controllers of an AngularJS application as the brain. The controllers are super smart and can define what happens on the (DOM) Document Object Model. AngularJS controllers along with the dependency injection form the super power of the AngularJS.

Controllers

Here are some key details AngularJS: How to Begin.

  •  Controllers are attached to the DOM through the ng-controller directive. When a controller is initialized, a javascript object will be created and all the functions in the .controller method can be accessed.
  • The initial state for the Angular $scope is available at the point where a controller is registered. All the properties of the $scope can be defined in the controller and can be accessed through the methods.
  • The .controller method can be used to add the controller’s constructor function to the module. Thus the constructor function is out of global scope.
  • Apart from the $scope, we can send additional parameters to the controller, such as services and functions. It is better to keep a controller as simple as possible. You can define as many controllers as you want in an AngularJS application.
  • A common practice of keeping controllers focused on the required logic is to define services and functions, which can in turn be passed to a controller through dependency injection.
  • Controllers can be nested and inherited. You have to note that the parent’s controller’s methods can be accessed in the child controller. And not vice versa.
  • Finally, remember that the controllers contain Javascript functions and are created by a standard Javascript object constructor and is bounded to a particular scope.

Example

Here is an example of how the Controller is initiated. You have to create an angular app called myapp. Also, you need to declare in the html to tell that it is an Angular application.

In the js:

myapp.controller(“MyCtrl”, function($scope){

$scope.message=”Hello”;

});

In the HTML or template:

<div ng-controller=”MyCtrl”>

{{message}}

<\div>

Your div is binded to the controller using the ‘ng-controller’ directive. The scope of the div is passed to the controller. The scope message variable’s value can be accessed in the div within the dual curly braces. Notice, how the name of the controller is defined with an ‘Ctrl’ and the double quotes used while defining and accessing the controller.

Similarly, you can have any number of controllers in your AngularJS application. You can have different Javascript files for each controller or just put it in one main file. This makes two way data binding easier and keeps your application simple!