Online Snippets Library

Create Simple Controller in AngularJS

In Below example we have perform twoway data binding with help of AngularJS Controller.AngularJS Controller is a JavaScript Object."ng-controller" directive is used to define application controller.

AngularJS Controller contains business logic behind the application to decorate the scope with functions and values.Here we define controller as JavaScript function.

AngularJS Controller creates a new scope, so we can define our model variables on that scope.We can also define functions on the "$scope" object.

Example

HTML
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body ng-app >
<div ng-controller="simpleController">
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> {{lastName}}</span><br />
<strong>Full name:</strong> {{getFullName()}}<br />
<label>Set First name: <input type="text" ng-model="firstName"/></label><br />
<label>Set Last name: <input type="text" ng-model="lastName"/></label>
</div>
</body>
</html>
JavaScript
var simpleController = function ($scope)
{
  // Initialize the model variables
  $scope.firstName = "Max";
  $scope.lastName = "Joe";
  // Define utility functions
  $scope.getFullName = function ()
  {
return $scope.firstName + " " + $scope.lastName;
  };
};