使用 ui-router 的单个状态下的多个视图共享单个控制器

multiple views in a single state sharing a single controller using ui-router

我已经按照下面的说明定义了我的状态,

模板如下所示,

     <div class="row-fluid">
        <section class="header">
            <div ui-view="header"></div>
        </section>

        <section class="content">
            <section class="actions">
                <div ui-view="action-bar"></div>
            </section>
        </section>

        <section class="footer">
            <div ui-view="footer"></div>
        </section>
    </div>


  .state('authenticated', {
        url: '/home',
        templateUrl: 'html/appShell.html'
    })
    .state('basicLayout', {
        parent: 'authenticated',
        url: '^/start',
        ***controller: 'abcController',***
        views: {
            '': {templateUrl: 'html/templates/basicLayout.html'},
            'header@basicLayout' : { 
               templateUrl:'html/templates/header.html',
                controller: 'abcController'},
            'action-bar@basicLayout' : { 
                templateUrl: 'html/templates/action-bar.html',
                controller: 'abcController'}
        }        
    })

我有一个 json 文件,它基本上包含模块名称的数据,它进入 header 并且操作栏是一个指令,它需要来自配置的按钮和操作类型的信息对于在 json.

中传递的每个按钮

我的问题是我可以关联一个共享控制器以从 module.json 读取数据并映射 $scope 变量,或者每个视图是否应该例如 header 它应该有一个单独的控制器和操作条形视图有一个单独的控制器。

我不想每个视图都有多个控制器,想知道最好的方法是什么???

回答你的问题。是的,您可以拥有一个包含范围变量数据的控制器,并通过路由在不同的视图中访问该数据。

首先,您为 json 返回的数据对象数组设置了一个变量。在不知道您的数据是什么样子的情况下,让我们假装您的 "data" 对象看起来像这样。

{  
   "thingsforview1" : [ //lots of objects here ],
   "thingsforview2" : [ //lots of objects here ],
   "thingsforview3" : [ //lots of objects here ]
}

您可以在控制器上为该数据设置一个变量,名为:

$scope.data = theJsonDataIGot;

在每个视图中,绑定到您需要的数据。您可以为每个视图使用单独的 .html 模板。

即在视图 1 中:

<ul>
    <li ng-repeat="thing in data.thingsforview1">
        {{ thing }}
    </li>
</ul>

即在视图 2 中:

<ul>
    <li ng-repeat="otherthing in data.thingsforview2">
        {{ otherthing.name }}
    </li>
</ul>

Return 不同的模板取决于 url。

app.config(['$routeProvider',
      function($routeProvider) {
        $routeProvider.
          when('/view1', {
            templateUrl: 'views/view1.html'
          }).
          when('/view2', {
            templateUrl: 'views/view2.html'
          }).
          otherwise({
            redirectTo: '/'
          });
      }]);

您将包括以下标记:

<div ng-view></div>

这是点击不同的 url 时显示不同模板的地方。

希望对您有所帮助!

编辑

对您当前拥有的内容的简单更改是,将单个控制器、页眉和页脚更改为指令,以及确定内容视图的状态。

<div ng-controller="abcController">
    <div class="row-fluid">
            <section class="header">
                <div my-header></div>
            </section>

            <section class="content">
                <section class="actions">
                    <div ui-view="action-bar"></div>
                </section>
            </section>

            <section class="footer">
                <div my-footer></div>
            </section>
     </div>
</div>

然后您可以从状态切换视图并仍然使用页眉和页脚的模板,以及从状态切换视图的内容。或者,如果页眉和页脚的内容也发生变化,请将这些指令包含在不同视图的模板中。