AngularJS Tutorial - AngularJS Scopes








Scopes is the bridge between the controller and the view.

We can set any types on the $scope, including objects.

$scopes in AngularJS are arranged in a hierarchical structure that mimics the DOM. We can reference properties on parent $scopes.

This $scope object is the data model in Angular. All properties from $scope object are accessible to the view.

A new scope for child DOM elements creates a new execution context.

We should put the application logic in a controller and the data in the scope.

Root scope

Angular creates a binding from the root ng-app element to the $rootScope. This $rootScope is the parent of all $scope objects.





Example


<!doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
</head><!--from   ww  w. j  a  va 2 s.  com-->
<body>
  <div ng-app="myApp">
    <div ng-controller="MyController">
      Here is the data from scope:{{ myData }}
    </div>
  </div>

<script>
angular.module("myApp", [])
.controller("MyController", ['$scope', function($scope) {
      $scope.myData = "hi from scope";
}]);
</script>
</body>
</html>

The code above is rendered as follows: