Angular JS Route:附加多个控制器

时间:2014-12-29 17:16:46

标签: javascript angularjs angular-routing

可以将多个控制器连接到路由,例如控制器阵列吗?

' / store' 中,我需要附上" StoreController"和" ReviewController" ,不多次重复 .when()

我的代码:

angular  
  .module('gemStore', [
    'example-directives'
  ])
  .config(function ($routeProvider) {

    $routeProvider

      .when('/store', {
        templateUrl: 'store.html',
        controller: 'StoreController'
      })

      .when('/store', {
        templateUrl: 'store.html',
        controller: 'ReviewController'
      }) 

      .otherwise({
        redirectTo: '/'
      });

  });

1 个答案:

答案 0 :(得分:4)

应该发生的事情是你应该只为一个页面设置一个“根”控制器,并且页面的任何“部分”应该是根控制器的子节点。

$routeProvider

  .when('/store', {
    templateUrl: 'store.html',
    controller: 'StoreParentController'
  })

然后可以在HTML中声明子项:

<div ng-controller="StoreParentController"> <!-- you dont need this particular controller here because you have it in your routeprovider, this is just an example of the structure-->
    <div ng-controller="StoreController"> stuff about store </div>
    <div ng-controller="ReviewsController"> reviews </div>
</div>