ng-controller

Description

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 ww.  j  a va 2  s.  co 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>

Click to view the demo

Example 2

The following code shows how to use hierarchical controllers.


<!--  w ww  .  j  a v  a2s .co  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>

Click to view the demo





















Home »
  AngularJS »
    AngularJS Tutorial »




Introduction
Buildin Filters
Buildin Directives