【发布时间】:2013-09-01 19:20:18
【问题描述】:
我有两个独立的视图(名为 view1.html 和 view.html),带有独立的控制器(名为 controller1 和 controller2),它们使用配置进行路由:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/view1', {templateUrl: 'view1.html', controller: controller1}).
when('/view2', {templateUrl: 'view2.html', controller: controller2}).
otherwise({redirectTo: '/view1'});
}]);
view1 和 view2 有一个共享的模板代码部分,所以我将它提取到一个新的模板视图(名为 view3.html)并在 view1.html 和 view2.html 中使用 ng-include:
<span ng-view="">
...
<span ng-include="'view3.html'"></span>
....
</span>
view3.html 的逻辑也独立于控制器 1 和控制器 2,因此 veiw3.html 中所需的范围变量在两个控制器中重复:
function controller1($scope){
...
some code to calculate $scope variables for view3
...
}
function controller2($scope){
...
same code to calculate $scope variables for view3
...
}
我的问题:有没有办法将控制器中的重复代码提取到 view3 的单独控制器中?我为 view3 添加了 ng-controller,但它不起作用:
<span ng-controller="controller3">
view3.html template codes here
</span>
我猜是因为 view3.html 包含在带有 ng-view 指令的元素中,并且不能有单独的控制器。
【问题讨论】:
-
我的理解是,规范的方法是将公共控制器代码重构为服务,并从您的控制器中调用它。我对角度有点陌生,但我读过的东西表明这是“正确”的方式。
-
这应该可以。那里有什么问题?
标签: javascript angularjs