Tuesday, February 24, 2015

$scope object

In the previous posts we saw on how to use the ng-bind directives to bind objects/properties to the view, in this post we shall see on how to use the $scope object to bind data the controller and the view.
The $scope is a JavaScript object which binds the controller and the view in an AngularJS MVC application. Both the controller and the view can access the $scope object, 2 way binding between the model and view is enabled using the $scope object.

In complex applications where we have the view and controller in different files we explicitly use the $scope object in the view to refer to the properties and methods defined in the model object.

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 = 'FirstName';
   $scope.LName = 'LastName';
      }
    </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>


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: