【问题标题】:angularjs single page share the same DIV elementangularjs单页共享同一个DIV元素
【发布时间】:2014-05-19 18:34:59
【问题描述】:

我尝试用 angularjs 实现单页应用

有路线代码:

angular.module('todomvc', ['ngRoute'])
    .config(function ($routeProvider) {
        'use strict';

        $routeProvider.when('/account', {
            controller: 'TodoCtrl',
            templateUrl: 'account.html'
        }).when('/', {
            controller: 'TodoCtrl',
            templateUrl: 'todomvc-index.html'
        }).otherwise({
            redirectTo: '/'
        });
    });

单页的html是:

<!doctype html>
<html lang="en" data-framework="angularjs">
    <head>
    <link rel="stylesheet" ... >
    <script ...></script>   
    </head>
    <body ng-app="todomvc">
        <ng-view />

        <script type="text/ng-template" id="account.html">
              a html template segment(*) here  
              ///////////// this is the template of the first appearance. //////////////
        </script>    

        <script type="text/ng-template" id="todomvc-index.html">
              the same html template segment(*) here 
              ///////////// this is the template of the second appearance. //////////////
              But both appearance share a common template segment. How to remove the duplication?
        </script>
    </body>
</html>

默认显示第二页。用户点击第二页的按钮后,会触发$location.path("account");并路由跳转到第一页。在我的例子中,两个模板共享一个 div 块,也就是说,一个共同的部分是加载到两个模板。目前,模板段被复制并粘贴到两个区域,如上面的代码所示。但是复制粘贴很难维护。如何在两个 text/ng-template 之间共享模板段?

谢谢。

【问题讨论】:

  • 您可以将共享的 html 放在一个单独的文件中,并使用 ng-include 包含该 html
  • 不确定 ng-include 是否可以在
  • 试一试...如果不行请告诉我...,我想应该可以...
  • 我之前确实试过了,但是没用。所以不确定,是它不起作用,还是因为我的代码不正确..
  • 应该是
    ' 是必须的,即在ng-include src 中需要一个javascript表达式

标签: angularjs


【解决方案1】:

在单独的 .html 文件中定义您的公共 div,并使用 ngInclude 指令将其包含在内。

<ng-include src="commonDiv.html"/>

【讨论】:

    【解决方案2】:

    我强烈推荐一个名为 ui-route 的模块,它提供了一种简单易用的方法来维护嵌套视图和模板。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      相关资源
      最近更新 更多