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

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

问题描述

我正在尝试构建视图-我设置了两个控制器进行练习,一个是HeaderCtrl,其中包含一些数据(网站标题,标题背景等),另一个应该具有页面的主要内容-MainCtrl.

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'
   })
})

这是行不通的,所以我猜这不是做到这一点的方法.我实际上要问的是-您可以在$ routeProvider中指定多个控制器吗?还是构建此视图的正确方法是什么?

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 ?

推荐答案

我要解决此问题的方法是有两个指令-标头和main,它们引用相应的模板.

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

例如:

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

然后,您将拥有一个包含指令的页面- index.html .

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

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

然后有一个一个控制器,该控制器可路由到您的index.html

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.

例如

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

或模板本身

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

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