首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角指令,用于检查子元素的数量

角指令,用于检查子元素的数量
EN

Stack Overflow用户
提问于 2016-06-15 09:36:08
回答 2查看 97关注 0票数 0

因此,我有一个简单的ul,ng-重复来自外部源的li元素,并承诺。我还有一个搜索输入,可以过滤这些元素,当ul不包含满足搜索要求的元素时,我希望它能够隐藏起来。

我制定了这个指令,但没有用:

代码语言:javascript
复制
.directive('predictive', function() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            console.log(element);
            if (!$(element).children("li").length) {
                $(element).hide();
            }
        }
    }
});

但是这个指令隐藏了所有的东西,因为它应用得太快了,在获取数据的服务用li来填充列表之前。

我能做些什么吗?

编辑:标记

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-15 10:03:49

您可以使用ng-repeat的筛选别名并在ng-if中检查该长度。

代码语言:javascript
复制
<ul ng-repeat="(key, option) in Service1.predictive" ng-if="filteredArray.length">

        <li ng-repeat="option in option | filter:predictiveSearch as filteredArray">

        </li>
</ul>
票数 3
EN

Stack Overflow用户

发布于 2016-06-15 10:08:29

您可以尝试使用<ul ng-repeat="(key, option) in Service1.predictive" ng-hide="(option | filter:predictiveSearch).length == 0">,而不是创建自定义指令。

你的选择会被过滤两次。如果其中有很多,最好是在自定义指令中进行过滤,以便只执行一次,并使用element.hide()而不是ng-hide隐藏元素。

代码语言:javascript
复制
.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"上进行迭代,并在指令中完成一次筛选。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37831603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档