Noor Noor - 2 months ago 11
AngularJS Question

Angular JS Error with Parent Child controller

I am getting a weird error with angular controllers. The error is reproduced on this JSFiddle
A sample of HTML:

<div ng-app>
<div ng-controller="GroupViewerController">
<table class="table table-striped">
<tr ng-repeat="a in arr" ng-controller="OneGroupViewerController">
<td >{{a}} <button ng-click="change(a)">change</button></td>
</tr>
</table>
</div>
<div ng-controller="oneGroupItemsController">
<input type="text" ng-model="$parent.selectedObject">
</div>
</div>


JavaScript:

function GroupViewerController($scope) {
$scope.selectedObject = "test";
$scope.arr = ["a","b"]
}

function OneGroupViewerController($scope) {
$scope.change = function (a){
$scope.$parent.selectedObject = a;
}
}

function oneGroupItemsController($scope) {

}


Errors:


  1. Why does "test" not appear in the textbox though the parent controller object has been referenced

  2. when the button change is pressed, why does the textbox contains the new value of
    selectedObject


Answer

You have made minor mistakes and also its not a good idea to use ng-controller with ng-repeat.

HTML:

<div ng-app>
  <div ng-controller="GroupViewerController">
          <table class="table table-striped" >
                <tr ng-repeat="a in arr" ng-controller="OneGroupViewerController">
              <td >{{a}} <button ng-click="change(a)">change</button></td>
                </tr>
            </table>
  <div ng-controller="oneGroupItemsController">
    <input type="text" ng-model="$parent.updateVar.selectedObject">
  </div>
  </div>

  </div>

JS:

function GroupViewerController($scope) {
  $scope.updateVar = {};
  $scope.updateVar.selectedObject = "test";
  $scope.arr = ["a","b"]
}

function OneGroupViewerController($scope) {
  $scope.change = function (a){
       $scope.$parent.updateVar.selectedObject = a;
  }
}

function oneGroupItemsController($scope) {

}

Working fiddle : https://jsfiddle.net/3L4gg6jv/7/

Comments