繁体   English   中英

如何为Angular.js中的包含视图定义单独的控制器?

[英]how to define separate controller for an included view in Angular.js?

我有两个单独的视图(分别名为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指令的元素中,并且不能具有单独的控制器。

我认为您可以使用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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM