我有两个单独的视图(名为view1.html和view.html),带有单独的控制器(名为controller1和controller2),并使用config路由它们:
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逻辑独立于controller1和controller2,因此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指令的元素中,并且不能有单独的控制器。
答案 0 :(得分:0)
我认为您可以使用ng-include
来实现它:
在view1.html
中<div ng-include src="'view3.html'"></div>
//other template for view1
在view2.html
中<div ng-include src="'view3.html'"></div>
//other template for view2
在view3.html
中<div ng-controller='controller3'>
//template for view3
</div>