Controllers in AngularJS

The continuation of the earlier post: the controller definition is

var myApp = angular.module("myModule", []);

myApp.controller("myController",function ($scope) {
$scope.message = "Angular JS Tutorial";
});

The job of the controller is to build a model for view. By attaching the model to scope, scope object is not a modal, the data attaching to the scope object is a modal.

We can attach complex variables to the scope object,

Lets have one small example:

var employee = {
firstName: "David",
lastName: "Hastings",
gender: "Male"
};

$scope.employee = employee;

First Name : {{employee.firstName}}
Last Name : {{employee.lastName}}
Gender : {{ employee.gender}}

What will happen if the controller name is misspelled
When the controller name is misspelled, 2 things happen

    --> An error is raised. To see the error, Use Browser developer tools
    --> The binding expressions in the view that are in the scope of the controller
    will not be evaluated

What happend if a property name in the binding expression is misspelled
Expression evaluation in angular is forgiving, meaning if you misspell a property name in the binding expression, angular will not report any error. it will simply return null or undefined.
Use the method chaining mechanism as shown below

var myApp = angular
.module("myModule",[])
.controller("myController", function($scope) {
var employee = {
firstName: "David",
lastName: "Hastings",
gender: "Male"
};
$scope.employee = employee;
});

0 thoughts on “Controllers in AngularJS

Leave a Reply

Your email address will not be published. Required fields are marked *