top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is controller in AngularJS?

+1 vote
376 views

A controller is a set of JavaScript functions which is bound to a specified scope, the ng-controllerdirective. Angular will instantiate the new controller object, and injects the new scope as a dependency. It contains business logic for the view and avoids using controller to manipulate the DOM. 

controller

Controller Rules

  • We can use controller to set up the initial state of the scope object and add behavior to that object.
  • We do not use controller to manipulate DOM. It should contain only business logic and can use data binding and directives for the DOM manipulation.
  • We do not use controllers to format input but can use angular from controls instead of that.
  • We do not use filter output but can use angular filters instead of that.
  • We do not use controllers to share code or state across controllers but can use angular services instead of that.
  • We do not manage the life-cycle of other components.

Creating a Controller

  • Requires ng-controller directive.
  • Add controller code to a module.
  • Name your controller based on functionality.
  • Controllers are named using camel case (i.e. SimpleController).
  • Setup the initial state of the scope object.

ng-Controller directive

ng-Controller directive is an associated controller class to the view.

How to use ng-Controller

<Any ng-Controller=”expression”>  

</Any>  

<div ng-app="mainApp" ng-controller="SimpleController">  

</div>  

posted Sep 28, 2017 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

AngularJS module is nothing but a container of all angular components like controller, services, directive, filter, config etc

What is Module

Let me explain why module is required in AngularJS. In .NET console application there is a main method and what main method does is, it’s an entry point of application. It is the same as angular module and is an entry point. Using module we can decide how the AngularJS application should be bootstrapped.

We can create a simple module using the following code.

var myApp = angular.module(‘myModuleApp’,[]);   

In the above code myModuleApp is the module name and if this module is dependent on other modules we can inject in “[]”.

What is Controller?

Controller is a JavaScript constructor function which controls the data. I am not going to cover what are the types of functions in this article but let me give some brief information about constructor function. In constructor function when we call that function that function creates a new object each time.

Let’s make a controller.

myApp.controller(‘myController’, function($scope)  

{  

  

});  

controller

READ MORE
...