在 angularjs 中为多个控制器路由? [英] Routing in angularjs for multiple controllers?

查看:17
本文介绍了在 angularjs 中为多个控制器路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个视图 - 我已经设置了两个控制器来练习,一个是 HeaderCtrl,里面有一些数据(站点标题、标题背景等),另一个应该有页面的主要内容- MainCtrl.

在定义路线时,我是这样做的:

mainApp.config(function ($routeProvider) {$routeProvider.什么时候('/',{控制器:'MainCtrl',templateUrl: 'modules/dashboard.html'})})

这工作得很好,但我想要的是为此指定多个参数,如下所示:

mainApp.config(function ($routeProvider) {$routeProvider.什么时候('/',{控制器:'HeaderCtrl',templateUrl: 'modules/header.html'},{控制器:'MainCtrl',templateUrl: 'modules/dashboard.html'})})

这行不通,所以我猜这不是办法.我实际上在问什么 - 你能在 $routeProvider 中指定多个控制器吗?或者构建此视图的正确方法是什么?

解决方案

我解决这个问题的方法是使用两个指令 - 引用相应模板的 header 和 main.

例如:

app.directive('header', function () {返回 {限制:'A',替换:真的,templateUrl:'templates/header.html'}})

然后你可以有一个包含指令的页面 - index.html.

<div主></div>

然后让一个控制器路由到您的 index.html

如果你想分开处理它们,你也可以将header和main封装在单独的header和main控制器中.

例如

<div 标题></div>

<div ng-controller="MainCtrl"><div主></div>

或使用模板本身

I'm trying to build a view - I've set up two controllers to practice, one's HeaderCtrl, with some data in it (site title, header background, etc), the other should have the main content of the page - MainCtrl.

When defining the route, I'm doing like so:

mainApp.config(function ($routeProvider) {
$routeProvider
   .when('/',
   {
       controller: 'MainCtrl',
       templateUrl: 'modules/dashboard.html'
   })
})

This works perfectly fine, but what I would want is to specify multiple parameters to this, something like this:

mainApp.config(function ($routeProvider) {
$routeProvider
   .when('/',
   {
       controller: 'HeaderCtrl',
       templateUrl: 'modules/header.html'
   },
   {
       controller: 'MainCtrl',
       templateUrl: 'modules/dashboard.html'
   })
})

This doesn't work so I'm guessing it's not the way to do it. What I'm actually asking - can you specify multiple controllers in $routeProvider ? Or what would be the correct way to build this view ?

解决方案

My approach to this problem would be to have two directives - header and main which reference the corresponding templates.

For Example:

app.directive('header', function () {
  return {
    restrict: 'A',
    replace: true,
    templateUrl:'templates/header.html'
  }
})

Then you can have a page that contains the directives - index.html.

<div header></div>
<div main></div>

Then have one controller that routes to your index.html

You can also encapsulate the header and main in separate header and main controllers if you want to deal with them separately.

e.g.

<div ng-controller="HeaderCtrl">
    <div header></div>
</div>
<div ng-controller="MainCtrl">
    <div main></div>
</div>

or with the templates themselves

这篇关于在 angularjs 中为多个控制器路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆