【问题标题】:How to use AngularJS features to insert multiple divs in one div (i.e. some kind of multi-element template)如何使用 AngularJS 功能在一个 div 中插入多个 div(即某种多元素模板)
【发布时间】:2013-05-30 13:33:25
【问题描述】:

在我的 AngularJS 应用程序中,我想做一些指令,将多个 HTML 元素插入到一个 HTML 元素中。

基本上,我希望 Angular 构建这个结果:

<div class="maindiv">
    <!-- Below are some divs common to all "maindiv" -->
    <div> ..XXX.. </div>
    <div> ..YYY.. </div>

    <!-- Below are some elements specific to maindiv1 -->
    <div> ..ABCD.. </div>
    <div> ..EFGH.. </div>
    <div> ..IJKL.. </div>
</div>

<div class="maindiv">
    <!-- Below are some divs common to all "maindiv" -->
    <div> ..XXX.. </div>
    <div> ..YYY.. </div>

    <!-- Below are some elements specific to this particular maindiv -->
    <div> ..1235.. </div>
    <div> ..5678.. </div>
</div>

...来自看起来像这样的 HTML:

<div class="maindiv" generate-common-stuff>
    <!-- Below are some elements specific to maindiv1 -->
    <div> ..ABCD.. </div>
    <div> ..EFGH.. </div>
    <div> ..IJKL.. </div>
</div>

<div class="maindiv" generate-common-stuff>
    <!-- Below are some elements specific to this particular maindiv -->
    <div> ..1235.. </div>
    <div> ..5678.. </div>
</div>

...或者像这样:

<div class="maindiv">
    <generate-common-stuff></generate-common-stuff>

    <!-- Below are some elements specific to maindiv1 -->   
    ...

当我尝试制作自己的指令时,Angular 抱怨我的模板中有多个根元素。

请注意,由于与其他库 (JQueryMobile) 不兼容,我无法在 div 下重新组合 &lt;div&gt; ..XXX.. &lt;/div&gt;&lt;div&gt; ..YYY.. &lt;/div&gt; 并在模板中使用它。它们必须插入到 maindiv 的正下方

您对如何实现它有任何想法吗?

【问题讨论】:

    标签: javascript html angularjs angularjs-directive


    【解决方案1】:

    尝试编写一个名为 generate-stuff 的指令,并将 commonspecific 作为属性传递,从范围绑定。

    <generate-stuff common="commonStuffInScope" specific="specificStuffInScope"></generate-stuff>
    

    ...在你的指令中

    myModule.directive('', function() {
      return {
        ...
        scope: {
          common: "=common",
          specific: "=specific"
        }
        ...
      };
    });
    

    因此,在链接函数中,您可以双向绑定作用域上的公共变量和特定变量。

    相关文档片段:http://docs.angularjs.org/guide/directive#directivedefinitionobject

    【讨论】:

    • 在我看来,常见和特定的东西不是作用域变量,而是整个 html 模板——可能包含对作用域变量的 {{ }} 引用。在我的应用程序中,每个 maindiv 都位于不同的 .html 文件中,理想情况下,我希望通用内容位于 .js 或 .html 文件中。
    • 然后你通过链接函数中的$attrs访问common和specific,并通过$http服务加载资源。您可以使用 $templateCache 来存储常见的东西。然后编译 dom 并使用 $compile 引用 $scope。
    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    相关资源
    最近更新 更多