Thursday, July 9, 2015

AngularJS Models

In the previous 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 models in AngularJS MVC architecture.

In AngularJS MVC architecture the $scope object represents the model, the $scope is accessible in both the controller and view and is used to bind data between controller and the view, AngularJS supports two-way data binding, this makes sure that any changes in the model object properties are reflected in the view and any change made by the user in the view layer gets reflected in the model ($scope) automatically.

The below example demonstrated the use of $scope object to bind between the model and 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:

Notice that the FName and LName properties are defined in the nameController under the $scope object, and are referenced in the view. The $scope can also hold complex object and reference between the controller and the view as follows.

controller

function personController($scope) {
    $scope.person = {
        firstName: "John",
        lastName: "David",
        fullName: function() {
            var x;
            x = $scope.person;
            return x.firstName + ", " + x.lastName;
        }
    };
}

View
<div ng-controller="personController">
          First Name: <input type="text" ng-model="person.firstName"><br>
          Last Name: <input type="text" ng-model="person.lastName"><br>
          Full Name: <b>{{person.fullName()}}</b>
</div>


Search Flipkart Products:
Flipkart.com

No comments: