gpt4 book ai didi

javascript - 当 AngularJS 中没有 ngRepeated 时,如何在我的 DOM 中排序?

转载 作者:行者123 更新时间:2023-11-30 05:40:12 25 4
gpt4 key购买 nike

我有一个 controller,它包含 2 个不同的 controller:usersclasses 模型。

我希望它们按照打开的时间顺序保持在顶部(例如,如果您打开 Users,然后打开 ClassesClasses 应该出现在 Users 之上,即使在 html 模板中,Users 部分首先出现)。这是一个 JSBin:

http://jsbin.com/IQUDEdI/10/edit

当您单击复选框打开一个部分时,它会取消移动将其移至array $scope.openSections。我意识到 ngFilter 不起作用,除非它在 ​​ngRepeat 中(对吧?)。

如果没有内置的方法(我正在查看 ngSwitch,但它看起来不像我想要的),我打算创建(或者更确切地说是修改) section 上的指令会执行 $(body).prepend(element) 或其他操作,但我不确定这是否 100% 有效。

有谁知道执行此操作的最佳方法吗?

提前致谢

最佳答案

这是个很好的问题。

基本上,我们需要一个指令来显示、隐藏和排序每个更改的部分列表。
我们的指令必须“知道”它包含的所有部分以便对它们进行排序。

哦,有这样一个指令:ngRepeat,但是我们如何才能为它提供一个部分列表呢?
如果这些“部分”只是 DOM 节点,则无法将它们传递到 ngRepeat

因此,我尝试创建一个收集所有 DOM NODES 的指令(容器),观察集合并更改排序、显示或隐藏相关部分。但是那种对 DOM 节点 的操作真的很痛苦,我觉得这是一种错误的方法。

然后我看到了光!

只需使用 ngInclude 来声明模板,稍微重构标记即可。
然后使用 ngRepeat 迭代这些模板,很好。

现在这是一场伟大的胜利:

  • 不需要自定义指令。
  • ngRepeat/ngInclude 的所有优点
  • 无需在每个部分设置不同的 watch ,ngRepeat 会处理它。
  • 简单明了!

这是一个 plunker :

声明模板:

<script type="text/ng-template" id="users.section">
<div ng-controller='usersviewer'>
<legend>Users</legend>
<li ng-repeat='user in users'>{{user.name}}</li>
</div>
</script>

<script type="text/ng-template" id="classes.section">
<div ng-controller='classesviewer'>
<legend>Classes</legend>
<li ng-repeat="class in classes">{{class}}</li>
</div>
</script>

使用 ngRepeat 完成所有“魔法”:

<div class='section' ng-repeat="include in openSections" ng-include="include + '.section'">
</div>

奖励 - 重构了 css 以匹配 ngInclude 动画:

.section {
background:darkgray;
color:white;

/* Default fully visible value */
opacity: 1;
height: 100px;
overflow:hidden;
}

.section.ng-leave {
/* Declare transitions */
display:block !important;
transition: all 0.2s;

/* Value when fully visible */
opacity: 1;
height: 100px;
}

.section.ng-leave-active {
/* Value when invisible */
opacity: 0;
height: 0px;
}

.section.ng-enter {
/* Declare transitions */
transition: all 0.2s;
display:block !important;

/* Value when invisible */
opacity: 0;
height:0px;
}

.section.ng-enter-active {
/* Value when fully visible */
opacity: 1;
height: 100px;
}

关于javascript - 当 AngularJS 中没有 ngRepeated 时,如何在我的 DOM 中排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21253620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com