由于我不会进入的原因,我没有使用ng-repeat作为项目列表。
我有一个这样的清单:
<p>Search: <input type="text" ng-model="search"></p>
<div id="grid" filter-list="search">
<div id="item1" class="[list of properties]">
//item content
</div>
<div id="item2" class="[list of properties]">
//item content
</div>
<div id="item3" class="[list of properties]">
//item content
</div>
<div id="item4" class="[list of properties]">
//item content
</div>
</div>
正如您所看到的,我已经有了一个很好的搜索功能。
我的应用脚本如下所示:
<script>
var app = angular.module('myApp', []).controller('MainCtrl', function ($scope, $timeout) {
});
app.directive('filterList', function ($timeout) {
return {
link: function (scope, element, attrs) {
var div = Array.prototype.slice.call(element[0].children);
function filterBy(value) {
div.forEach(function (el) {
el.className = el.textContent.toLowerCase().indexOf(value.toLowerCase()) !== -1 ? '' : 'ng-hide';
});
}
scope.$watch(attrs.filterList, function (newVal, oldVal) {
if (newVal !== oldVal) {
filterBy(newVal);
}
});
}
};
});
</script>
问题是我需要能够根据类值甚至id来重新排序列表(在这个阶段它并不重要)。
在线的每个教程/指南都假定代码使用&#34; ng-repeat&#34; ......我根本无法在这里使用。
有没有办法在不使用ng-repeat的情况下让物品重新排序?
答案 0 :(得分:0)
而不是使用ng-repeat
只对数据进行排序。
$ scope.items = $ scope.items.sort(yourSortFn);
答案 1 :(得分:0)
按照您需要的方式对元素数组进行排序,过滤或缩小,然后附加结果
使用降序ID的非常基本的示例:
scope.sortDesc = function() {
div.sort(function(a, b) {
return /\d+/.exec(b.id) - /\d+/.exec(a.id);
});
element.append(div);
}
scope.sortDesc();
答案 2 :(得分:0)
您可以修改此排序脚本:
<ul id="id01">
<li>Oslo</li>
<li>Stockholm</li>
<li>Helsinki</li>
<li>Berlin</li>
<li>Rome</li>
<li>Madrid</li>
</ul>
<script>
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("id01");
switching = true;
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("LI");
// Loop through all list items:
for (i = 0; i < (b.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Check if the next item should
switch place with the current item: */
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
/* If next item is alphabetically lower than current item,
mark as a switch and break the loop: */
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark the switch as done: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
</script>
只是定位div元素而不是li元素,并根据它们的.className属性(根据你得到的数据推导出它们)来比较它们,而不是它们的.innerHTML