【问题标题】:Angular ng-repeat with header views带有标题视图的 Angular ng-repeat
【发布时间】:2013-03-12 17:59:02
【问题描述】:

我知道ng-repeat的基本用法,我可以很容易地生成一个列表。

<ul>
  <li ng-repeat="presentation in presentations">
    {{presentation.title}}
  </li>
</ul>

我有一个从 PHP 返回的数组:

presentations = Array
(
    [0] => stdClass Object (
            [collection] => Collection A
            [title] => Title 1a
        )
    [1] => stdClass Object (
            [collection] => Collection A
            [title] => Title 2a
        )
    [2] => stdClass Object (
            [collection] => Collection B
            [title] => Title 1b
        )
    [3] => stdClass Object (
            [collection] => Collection B
            [title] => Title 2b
        )
    [4] => stdClass Object (
            [collection] => Collection C
            [title] => Title 1c
        )
    [5] => stdClass Object (
            [collection] => Collection C
            [title] => Title 2c
        )
    [6] => stdClass Object (
            [collection] => Collection C
            [title] => Title 3c
        )
)

您会注意到每个对象都有一个collection

我基本上需要为每个集合创建一个标题视图。我需要它显示如下:

COLLECTION A
    - Title 1a
    - Title 2a
COLLECTION B
    - Title 1b
    - Title 2b
COLLECTION C
    - Title 1c
    - Title 2c
    - Title 3c

只有标题是可点击的。这可能与ng-repeat 有关吗?我知道我可以在 PHP 中将每个集合排序到单独的数组中。我应该先这样做吗?如果可能的话,我想只使用ng-repeat,我只是不知道如何处理这个问题。

我计划在 nav-list 中显示此列表,使用 twitter 引导程序定义。

【问题讨论】:

    标签: php javascript twitter-bootstrap angularjs


    【解决方案1】:

    可能还有其他方法可以使用指令来实现这一点,但是

    http://beta.plnkr.co/KjXZInfrDK9eRid2Rpqf

    您定义了一个要调用的函数以显示或隐藏标题:

    // just a hard coded list of objects, we will output a header when the title changes
    $scope.presentations = [{"title":"a", "other":"something else"},{"title":"a", "other":"something else"},{"title":"b", "other":"something else"},{"title":"b", "other":"something else"}, {"title":"b", "other":"something else"}]
    $scope.currentTitle = '-1';
    $scope.CreateHeader = function(title) {
          showHeader = (title!=$scope.currentTitle); 
           $scope.currentTitle = title;
          return showHeader;
    }
    

    你的 html 看起来像这样:

    <ul>
        <li ng-repeat="presentation in presentations">
          <div ng-show="CreateHeader(presentation.title)">
            {{presentation.title}} is the header
          </div>
          {{presentation.other}} is an attribute on the collection item
       </li>
    </ul>
    

    【讨论】:

    • 应该是presentation in presentations,但不完全是。这实际上是在生成一个巨大的列表pastie.org/7083218
    • 这就像我需要存储上一个集合的值,然后当当前集合与上一个集合不同时,创建一个新的标题
    • 我做了一个调整,基本上你希望能够显示或隐藏一些东西,你可以使用 ng-show 指令来做到这一点,也可以传入一个函数将其保存回范围.我认为这个设置就是你所追求的。可能还有其他方法可以做到这一点,但首先想到的也是最简单的方法。
    • 太好了,这正是我所追求的!非常感谢
    • 你知道,现在我想到了,你说使用指令可能会更容易。如果您有一些空闲时间或想解决问题,您能否展示一个使用该指令的示例?我还没有使用指令。再次感谢上面的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2023-03-05
    • 2014-10-26
    • 1970-01-01
    • 2015-09-15
    相关资源
    最近更新 更多