I am facing a challenge regarding the extension of methods in an angular child controller which is causing me some frustration. My main objective is to inherit all the public /$scope/ variables and methods from the parent controller into the child controller, while also adding more functionality to specific functions. This is what I have so far:
var app = angular.module("conrollersInheritance", []);
app.controller("parentController", [
"$scope",
function ($scope) {
/* PRIVATE */
var privateVar1 = "private variable 1";
var privateVar2 = "private variable 2";
// ...Other private declarations...
/* 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);
};
// ...Other public functions...
}
]);
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`
};
}
]);
The issue I'm encountering is that the childController
is inheriting all the $scope
data from the parentController
, but I'm unable to extend the functionality inherited as it keeps getting overridden. I've tried various approaches based on Angular documentation which states 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 constructor object. When I try:
var parentController = $controller( "parentController", { $scope: $scope } );
I always get an empty object for the parentConroller
variable and cannot use anything inherited from it. I attempted to declare a viewmodel inside the childController
using:
var vm = this;
$controller( "parentController", { vm: $scope } );
angular.extend( $scope, vm );
However, this approach results in an error when trying to extend the scope. I also tried:
$scope.showVars = function() {
alert( "child scope" );
vm.showVars();
};
But still faced difficulties in implementing this. I have read many tutorials suggesting that the above methods should work, but they do not seem to be effective in my situation. Any suggestions or ideas would be greatly appreciated. Thank you!