AngularJs Controllers

HTML page can be divided into multiple sections to display information. If we want particular section of the page to have modifications according to database changes we can achieve that through controllers. Controllers acts like a bridge b/w view and model changes. We must not use controllers for DOM Manipulation other than holding model values. These controllers are no different from other framework controllers. For example while developing application using Servlets and Jsp’s we pass the data from view to controller and from controller we connect to data base and fetch the results and send back to view using controllers. In the similar fashion here also we use the controllers for the same purpose, but here there is no need to pass data to view they are binding using $scope of the controller to the view.

All scopes of the controller are created using prototypical inheritance. controllers can be nested which means that if value is not found on child controller’s scope then angular searches it in parent controller’s scope since angular follows prototypical inheritance.

Let’s see a simple example

<html ng-app>
    <script src="lib/angular.js"></script>
        function MyController($scope) {
            $scope.alphabet = "";
            $scope.$watch('alphabet', function(newVal, oldVal,scope){
               if(newVal.length === 1){
<body ng-app="">
<div ng-controller="MyController">
    <input type="text" ng-model="alphabet"/>
    <span ng-show="varStatus">{{alphabet}}</span>

In the above example I have defined a behavior for text field using “MyController” . Whenever there is only single letter or number or symbol it shows the typed one. For that I’am watching “alphabet” for changes and making “varStatus” true which gets reflected in view via defined controller scope.

Topics to know: controller hierarchy, nested controllers, $watch, prototypical inheritance


One thought on “AngularJs Controllers

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s