Thursday, July 9, 2015

AngularJS Controllers

In the post What is MVC Architecture? We saw the various layers of MVC architecture and we saw that that model is the representation of data in the MVC architecture. In this post we shall see more in detail about controllers in AngularJS MVC architecture

Controllers are the main components in the MVC architecture which controls the data and event flow in the application. Defining a controller is done in 2 parts, first we need to create a JavaScript controller function which accepts $scope as parameter, remember $scope is the representation of model in AngularJS MVC framework, next we need to reference the controller function in the view using the ng-controller directive. Once this is done any property/data defined in in the $scope in the controller function is made available in the view layer.

The below example defines a controller function nameController sets properties FName & LName to $scope in the controller function, the controller is tied to the view using ng-controller and the properties FName & LName are bound to the controls in the view.

<html ng-app>
  <head>
    <meta charset="utf-8">
    <title>AngularJS - Basic</title>
    <script src="angular.min.js"></script>
    <script>
      function nameController($scope){
              $scope.FName = 'John';
              $scope.LName = 'David';
      }
    </script>
  </head>
  <body>
          <div ng-controller="nameController">
                   First Name: <input type="text" ng-model="FName"><br/><br/>
                   Last Name: <input type="text" ng-model="LName"><br/><br/>
                   Your Name is :{{FName}}, {{LName}}
          </div>
  </body>
</html>

Output:



Search Flipkart Products:
Flipkart.com

1 comment:

sindhuja cynixit said...

Thank you for sharing valuable information.Angularjs online training