【问题标题】:Angular JS embedding same template in many other templatesAngular JS 在许多其他模板中嵌入相同的模板
【发布时间】:2023-03-20 08:48:01
【问题描述】:

我正在尝试使用测试应用程序(从 AngularJS 种子项目开始)学习 AngularJS,其中涉及用户会话。用户登录后,有多个视图。我为他们使用不同的部分。现在我的问题是,我想在应用程序内的所有视图中显示用户名和注销链接。

我能想到的唯一方法是在所有视图中为用户名和注销按钮添加所需的 html,并在每个控制器的范围内添加所需的数据。 我认为这不是正确的做法。

我知道ui-router。但我无法使用它。

使用路由器或其他方法,我想实现这样的目标:

主要的html:

<div ng-view><!-- Main DIV -->
    <div><!-- Login partial comes here, if not logged in or else app partial will be displayed--></div>
</div>

应用部分:

<div>
  <div class='userInfo'><!-- userInfoPartialTemplate here --> </div>
  <div><!-- any other app partial template will be filled according to the url --></div>
</div>

任何建议或链接将不胜感激!

谢谢!

【问题讨论】:

  • ngInclude 可能是您正在寻找的。​​span>
  • @jaux:不,它不工作。它看起来像 ng-include 仅在您将其放在主 html 页面中时才有效。但是,我的要求是在另一个模板中使用它。你有什么想法吗?
  • 我只是在小提琴中试了一下。不工作。
  • 用单引号将src 包裹起来:)
  • 太棒了!我已经创建了一个答案,其中包含您可能感兴趣的更多信息。

标签: javascript angularjs


【解决方案1】:

ngInclude 指令是你需要的doc。您可以尝试像这样使用ngInclude

<div>
  <div class='userInfo'><!-- userInfoPartialTemplate here --> </div>
  <div ng-include="'your-app-partial.html'"></div>
</div>

请注意,您的模板 URL 用单引号括起来!

此外,您可以使用角度表达式在ngInclude 中指定模板URL。例如,您有一个范围变量来保存模板 URL,您事先不知道该值是什么,您的控制器如下所示:

function Ctrl($scope) {
    $scope.subTemplate = 'your-app-partial.html'; // I use static string here for simplicity, but it could be anything that gives you the template URL...
}

subTemplate 变量保存模板的 URL 值,现在您的 HTML 应该如下所示:

<div ng-controller="Ctrl">
  <div class='userInfo'><!-- userInfoPartialTemplate here --> </div>
  <div ng-include="subTemplate"></div>
</div>

创建此plunk 是为了展示这个想法。

【讨论】:

    猜你喜欢
    • 2016-08-15
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多