Sampath Sampath - 4 months ago 39
AngularJS Question

Cannot Access parent controller's method from the child UI

I have a popup form where it's having lot of tabs.

Its' like this :

index.js

vm.openCreateOrEditPropertyModal = function (resolveProperty) {
var modalInstance = $uibModal.open({
templateUrl: '~/App/tenant/views/propertymanagement/createOrEditPropertyModal.cshtml',
controller: 'tenant.views.propertymanagement.createOrEditPropertyModal as vm',
resolve: {
resolveProperty: function () {
return resolveProperty;
}
}
});
};


Tabs are like this :

createOrEditPropertyModal.cshtml

<uib-tabset class="tab-container tabbable-line" type="pills">
<uib-tab heading="@L("PropertyInformation")">
<div ng-include="'~/App/tenant/views/propertymanagement/tabs/propertyForm.cshtml'"></div>
</uib-tab>
</uib-tabset>


createOrEditPropertyModal.js

(function () {
appModule.controller("tenant.views.propertymanagement.createOrEditPropertyModal", [
"$scope", "resolveProperty", "localStorageService", "$uibModalInstance", function ($scope, resolveProperty, localStorageService, $uibModalInstance) {

var vm = this;


//to close the pop up
vm.cancel = function () {
$uibModalInstance.close();
};
}
]);
})();


propertyForm.cshtml

<div ng-controller="tenant.views.propertymanagement.tabs.propertyForm as vm">
<button type="button" ng-click="vm.cancel()">@L("Close")</button>
</div>


propertyForm.js

(function () {
appModule.controller("tenant.views.propertymanagement.propertyForm", [
"$scope", "resolveProperty", "localStorageService", function ($scope, resolveProperty, localStorageService) {

var vm = this;



}
]);
})();


Above set up is working fine.Now I need to access
cancel()
method on the
createOrEditPropertyModal.js
file from the child form (i.e.
propertyForm.cshtml
).But it's not being fired.Can you tell me how to do that ? I have tried like this
ng-click="$parent.cancel()"
.But it's not working.

Answer

You can do vm.cancel() directly inside a child form as you are already using controllerAs pattern. But in your case you have both controller alias as vm it is referring to current child controller context. Changing name of either of controller alias would make it working.

Best way to solve this issue would change your controller alias to different name. Controller aaliases should be like by looking at their name's you can pretend which controller it is.

--

The ng-click isn't working because cancel method isn't there inside $parent scope. You should be doing $parent.vm.cancel(). But I'd not prefer you to use $parent on view, because bad practice.