Monday, July 6, 2015

$scope service in AngularJS

$scope is the most commonly used built-in service in AngularJS, $scope acts as the model object, it glues the controller with the view, $scope holds the objects/properties. $scope enables 2-way binding between the view and the model, properties of $scope can be set in the controller and bound to the object, any changes made in the view will get automatically reflected in the $scope.

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>

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: