3

I am changing value of variable inside child controller using $scope.$parent but change is not reflecting to its parent.

<div data-ng-if="!addBillDetails">
    <button class="btn btn-small" data-ng-if="trItem.skuId==217"
            data-ng-click="addDetails()">Add Details</button>
</div>
<div data-ng-if="addBillDetails" data-ng-include="'views/test.html'"></div>
$scope.addDetails=function(){
                $scope.addBillDetails=true;
};

test.html and testCrl

<div data-ng-controller="testCtrl">
<button type="button" class="btn red" data-ng-click="cancel()">Cancel</button>
    </form>
</div>
$scope.cancel=function(){
   alert("cancel");
  $scope.$parent.addBillDetails=false;
};
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Keshav
  • 821
  • 2
  • 12
  • 33

1 Answers1

3

This is happening because ng-include/ng-if creates a prototypically inherited child scope.

Let's begin with why $parent trick didn't work for you, basically addBillDetails variable wasn't allocated in immediate $parent scope of testCtrl. Since views/test.html template gets rendered based on ng-if & ng-include directive combination. It creates different scope hierarchy, refer below diagram.

//ng-controller="parentCtrl" `$scope.addBillDetails`
|
|
ng-if
   |
   |- ng-inlcude
      |
      |- ng-controller="testCtrl" ($scope.$parent.$parent.$parent.addBillDetails)

By looking at above diagram, if you want to modify addBillDetails of parent testCtrl, the you have to use $scope.$parent.$parent.$parent.addBillDetails in order to get hold of correct value. Check demo here. Never use $parent in your code, that makes your code tightly couple html design & assumption.


In such cases using object (reference type variable) are preferred or using controllerAs pattern while using controller ( controllerAs version).

Recommend to read on "What are the nuances of scope prototypal / prototypical inheritance in AngularJS?"

Html

{{model.addBillDetails}}
  <div data-ng-if="!model.addBillDetails">
    <button class="btn btn-small" data-ng-if="trItem.skuId==217" data-ng-click="addDetails()">Add Details</button>
  </div>
  <div data-ng-if="model.addBillDetails" data-ng-include="'views/test.html'"></div>

Code

.controller('parentCtrl', function($scope) {
    $scope.model = {};
    $scope.model.addBillDetails = true;
    $scope.addDetails = function() {
      $scope.model.addBillDetails = true;
    };
})
.controller('testCtrl', function($scope) {
    $scope.cancel = function() {
      alert("cancel");
      $scope.model.addBillDetails = false;
    };
})

Preview

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299