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