用于检查子元素数量的Angular指令

时间:2016-06-15 09:36:08

标签: javascript angularjs attributes promise directive

所以我有一个简单的 ul ,来自外部源的ng-repeats li 元素与promise一起收集。我还有一个过滤这些元素的搜索输入,我希望 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>

2 个答案:

答案 0 :(得分:3)

您可以使用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>

答案 1 :(得分:1)

您可以尝试<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"并在你的指令中完成一次过滤。