AngularJS Tutorial - Share Models Between Nested Controllers








The following code shows how to share Models Between Nested Controllers.

Example


<!doctype html>
<html ng-app="MyApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
    <script>
var app = angular.module("MyApp", []);
<!--from  www  .j a v a2 s.c o m-->
app.controller("MyCtrl", function($scope) {
  $scope.name = "XML";
  $scope.user = {
    name: "CSS"
  };
});

app.controller("MyNestedCtrl", function($scope) {
});    
    </script>

  </head>
  <body ng-app="MyApp">
    <div ng-controller="MyCtrl">
      <label>Primitive</label>
      <input type="text" ng-model="name">

      <label>Object</label>
      <input type="text" ng-model="user.name">

      <div class="nested" ng-controller="MyNestedCtrl">
        <label>Nested Primitive</label>
        <input type="text" ng-model="name"><br/>

        <label>Primitive with explicit $parent reference</label>
        <input type="text" ng-model="$parent.name"><br/>

        <label>Object</label>
        <input type="text" ng-model="user.name">
      </div>
    </div>
  </body>
</html>

The code above is rendered as follows: