关于在 Angular 子 Controller 中扩展的某些方法,我遇到了一个让我感到不安的问题。我的主要目标是将父 Controller 中的所有公共(public)/$scope/变量和方法继承到子 Controller 中,但用更多逻辑扩展一些特定功能。这就是我的一般情况:
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`
};
}
]);
所以基本上,childController
继承了parentController
的所有$scope
数据,这很好,但我似乎无法扩展功能继承,但总是覆盖它。我尝试了不同的方法来解决这个问题,因为我从 Angular 文档中看到 $controller
服务应该返回实例/https://docs.angularjs.org/api/ng/service/ $controller/,但就我而言,它总是返回一个空的构造函数对象。所以当我尝试在 childController
中执行类似的操作时:
var parentController = $controller( "parentController", { $scope: $scope } );
我总是为 parentConroller
变量获取一个空对象,并且我无法使用从那里继承的任何内容。尝试在 childController
中使用 viewmodel 声明,如下所示:
var vm = this;
$controller( "parentController", { vm: $scope } );
angular.extend( $scope, vm );
但似乎也不是正确的决定,因为它在尝试扩展范围时会引发错误,而且我也无法做这样的事情:
$scope.showVars = function() {
alert( "child scope" );
vm.showVars();
};
所以,我有点困惑我该怎么做。我读了很多教程,声称上述方法应该有效,但在我的情况下看起来并非如此。那么,有什么想法吗? 谢谢!
最佳答案
由于原型(prototype)继承,如果您的 Controller 是嵌套的,您的子 Controller 默认会从 $scope
继承所有父级的属性/方法。
您可以通过使用ui-router
并定义子状态来嵌套 Controller
.state('route', {
controller: 'ParentController',
// the rest of the route config
})
.state('route.child', {
controller: 'ChildController',
// the rest of the route config
})
或者将它们嵌套在模板中
<div ng-controller="ParentController">
<div ng-controller="ChildController">
<!-- the rest of your template -->
</div>
</div>
然后您可以简单地扩展您的 ParentController
方法,如下所示:
$scope.showVars = () => {
$scope.$parent.showVars();
// your other logic
};
这将在您的 ChildController
的 $scope
上创建一个 showVars
方法,默认情况下您的模板将使用该方法,而不是使用该方法继承自 ParentController
。
关于javascript - Angular : Inherited method extend in the child controller scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555630/