I've got a problem that is getting into my nerves regarding some methods extending in an angular child controller. My primary goal is to inherit all the public /$scope/ variables and methods from the parent controller into the child one, but extend some specific functions with more logic. So this is what I have in general:
var app = angular.module("conrollersInheritance", []);
app.controller("parentController", [
"$scope",
function ($scope) {
/* PRIVATE */
var privateVar1 = "private variable 1";
var privateVar2 = "private variable 2";
// ...Some other private stuff here...
/* PUBLIC */
$scope.publicVar1 = "public variable 1";
$scope.publicVar2 = "public variable 2";
$scope.showVars = function () {
console.log("PRIVATE: ", privateVar1, privateVar2);
console.log("PUBLIC: ", $scope.publicVar1, $scope.publicVar2);
};
// ...Some other public stuff here...
}
]);
app.controller("childController", [
"$scope", "$controller",
function ($scope, $controller) {
$controller("parentController", { $scope: $scope });
$scope.showVars = function () {
alert("child scope");
// ???Here I want to execute the inherited method from the `parentController`
};
}
]);
So basically, the childController inherits all the $scope data from the parentController which is fine, but I cannot seem to extend the functionality inherited, but always override it. I tried different approaches to solve the problem, because I saw from the Angular docs that the $controller service should return the instance / https://docs.angularjs.org/api/ng/service/$controller /, but in my case it always returns an empty contructor object. SO when I try to do something like this into the childController:
var parentController = $controller( "parentController", { $scope: $scope } );
I am always getting an emtpy object for the parentConroller variable and I cannot use anything inherited from there. Tried to use the viewmodel declaration inside the childController with something like this:
var vm = this;
$controller( "parentController", { vm: $scope } );
angular.extend( $scope, vm );
but also seems not to be the right decisions as it throws an error when trying to extend the scope and I cannot do anything like this as well:
$scope.showVars = function() {
alert( "child scope" );
vm.showVars();
};
So, I'm kind of stuck how can I do this. I read a lot of tutorials claiming that above methods should work, but it doesn't look like this in my case. So, any ideas? Thanks!
$scope.$parent.showVars()?