我迁移的AngularJS多页应用一个单页的应用程序,并且我有一些麻烦复制以下行为:不同的父控制器
每个HTML文件具有不同的基控制器和ng-view。例如,file1.html
看起来是这样的:
<body ng-controller="BaseCtrl1">
<!-- Routes to /view11, /view12, etc. with their corresponding controllers -->
<div ng-view></div>
</body>
<script src="file1.js"></script>
file2.html
使用BaseCtrl2
,路由到/views21
,/view22
等。每个这种控制器的初始化范围,及视相应子集共享模型的这一部分:
file1.js:
module.controller('BaseCtrl1', function($scope, ServiceA, ServiceB, ServiceC) {
// Populate $scope with ServiceN.get() calls
ServiceA.get(function(response) {
$scope.foo = response.results;
});
});
// ...
file2.js:
module.controller('BaseCtrl2', function($scope, ServiceX, ServiceY) {
// Populate $scope with ServiceN.get() calls
});
// ...
然而,随着我无法为每个不同的视图组使用固定父控制器(在body
元素中声明)的单页应用程序。我已经使用了$controller service像the answer of this question试过,但我需要注入的子控制器父的所有依赖,并且看起来并不像一个整洁的解决方案都:
module.controller('View11Ctrl', function($scope, ServiceA, ServiceB, ServiceC) {
$controller('BaseCtrl1', {/* Pass al the dependencies */});
});
module.controller('View12Ctrl', function($scope, ServiceA, ServiceB, ServiceC) {
$controller('BaseCtrl1', {/* Pass al the dependencies */});
});
我想知道有一种方法可以通过初始化一组视图的“常见”部分范围来复制原始行为,并在更改路线时对其进行维护。
你看过[AngularJS Inheritance Patterns](http://blog.mgechev.com/2013/12/18/inheritance-services-controllers-in-angularjs/)吗? – 2014-09-23 10:04:37
此外,它看起来可以完全重用所有控制器方法中的相同功能。 – 2014-09-23 10:07:22
另外,你可以嵌套控制器 - f.e.在外部标签上有BaseCtrl1,并且View11Ctrl只设置差异。范围是继承的。 – 2014-09-23 10:08:45