AngularJS Tutorial - ng-controller








ng-controller modifies the scope of directives. It creates a child scopes for the directives.

ng-app creates the $rootScope for an Angular application, while ng-controller creates a child scope from either $rootScope or parent ng-controller's $scope.

A child $scope is a JavaScript object that inherits methods and properties from its parent $scope(s), including the application's $rootScope.

Example

The following code shows how to ng-controller.


<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
</head><!--   w w  w .j a  v a2s  .  c o m-->
<body>

  <div ng-controller="SomeCtrl">
    {{ myModel.myProperty }}
    <button ng-click="clickHandler()">change</button>
  </div>

  <script>
    angular.module('myApp', [])
    .controller('SomeCtrl', function($scope) {
      $scope.myModel = {
        myProperty: 'init'
      }
      $scope.clickHandler = function() {
        $scope.myModel.myProperty = 'changed';
      };
    });
  </script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to use hierarchical controllers.


<!--   www  . jav  a2  s . c o  m-->
<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
</head>
<body>

  <div ng-controller="SomeCtrl">
    {{ myModel.myProperty }}
    <button ng-click="parentClickHandler()">Parent</button>
    <div ng-controller="ChildCtrl">
      {{ myModel.myProperty }}
      <button ng-click="childClickHandler()">Child</button>
    </div>
  </div>

  <script>
    angular.module('myApp', [])
    .controller('SomeCtrl', function($scope) {
      $scope.myModel = {
        myProperty: 'init'
      }
      $scope.parentClickHandler = function() {
        $scope.myModel.myProperty = 'from parent';
      };
    })
    .controller('ChildCtrl', function($scope) {
      $scope.childClickHandler = function() {
        $scope.myModel.myProperty = 'from child';
      };
    });
  </script>

</body>
</html>

The code above is rendered as follows: