Angular 检查子 li 元素数量的指令
Angular directive that checks for number of children li elements
所以我有一个简单的 ul,它 ng-repeats li 来自外部源的元素与承诺一起收集。我还有一个过滤这些元素的搜索输入,我希望 ul 在不再包含满足搜索的元素时隐藏。
我做了这个指令,但它不起作用:
.directive('predictive', function() {
return {
restrict: 'A',
link: function(scope, element) {
console.log(element);
if (!$(element).children("li").length) {
$(element).hide();
}
}
}
});
但是指令隐藏了所有内容,因为它应用得太快,在获取数据的服务用 li 填充列表之前。
我能做些什么吗?
编辑:标记
<input type="text" ng-model="predictiveSearch"></input>
<ul ng-repeat="(key, option) in Service1.predictive" predictive>
<span><b>{{key}}</b></span>
<li ng-repeat="option in option | filter:predictiveSearch">
<a href="" ng-click="handlePredictiveSelection(option)">{{option}}</a>
</li>
</ul>
您可以使用 ng-repeat
的过滤器别名并在 ng-if
中检查该长度
<ul ng-repeat="(key, option) in Service1.predictive" ng-if="filteredArray.length">
<li ng-repeat="option in option | filter:predictiveSearch as filteredArray">
</li>
</ul>
您可以尝试 <ul ng-repeat="(key, option) in Service1.predictive" ng-hide="(option | filter:predictiveSearch).length == 0">
而不是创建自定义指令。
这将过滤您的选项两次。如果它们很多,最好是在自定义指令中进行过滤,这样它只执行一次并使用 element.hide()
而不是 ng-hide
.
隐藏元素
.directive('predictive', function($filter) {
return {
restrict: 'A',
link: function(scope, element) {
var filter = $filter('filter');
scope.watch('predictiveSearch', function(value) {
scope.innerOptions = filter(scope.option, value);
if (!scope.innerOptions.length) {
element.hide();
}
});
}
}});
现在您应该能够迭代 innerOptions: ng-repeat="option in innerOptions"
并且在您的指令中完成一次过滤。
所以我有一个简单的 ul,它 ng-repeats li 来自外部源的元素与承诺一起收集。我还有一个过滤这些元素的搜索输入,我希望 ul 在不再包含满足搜索的元素时隐藏。
我做了这个指令,但它不起作用:
.directive('predictive', function() {
return {
restrict: 'A',
link: function(scope, element) {
console.log(element);
if (!$(element).children("li").length) {
$(element).hide();
}
}
}
});
但是指令隐藏了所有内容,因为它应用得太快,在获取数据的服务用 li 填充列表之前。
我能做些什么吗?
编辑:标记
<input type="text" ng-model="predictiveSearch"></input>
<ul ng-repeat="(key, option) in Service1.predictive" predictive>
<span><b>{{key}}</b></span>
<li ng-repeat="option in option | filter:predictiveSearch">
<a href="" ng-click="handlePredictiveSelection(option)">{{option}}</a>
</li>
</ul>
您可以使用 ng-repeat
的过滤器别名并在 ng-if
<ul ng-repeat="(key, option) in Service1.predictive" ng-if="filteredArray.length">
<li ng-repeat="option in option | filter:predictiveSearch as filteredArray">
</li>
</ul>
您可以尝试 <ul ng-repeat="(key, option) in Service1.predictive" ng-hide="(option | filter:predictiveSearch).length == 0">
而不是创建自定义指令。
这将过滤您的选项两次。如果它们很多,最好是在自定义指令中进行过滤,这样它只执行一次并使用 element.hide()
而不是 ng-hide
.
.directive('predictive', function($filter) {
return {
restrict: 'A',
link: function(scope, element) {
var filter = $filter('filter');
scope.watch('predictiveSearch', function(value) {
scope.innerOptions = filter(scope.option, value);
if (!scope.innerOptions.length) {
element.hide();
}
});
}
}});
现在您应该能够迭代 innerOptions: ng-repeat="option in innerOptions"
并且在您的指令中完成一次过滤。