首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Angular JS上预填入关键字搜索过滤器

在Angular JS上预填入关键字搜索过滤器
EN

Stack Overflow用户
提问于 2019-10-08 13:37:34
回答 2查看 146关注 0票数 1

我正在尝试加载一个在输入字段中预先填充了值的页面。页面和值确实会加载,但直到我在键盘上输入一些东西时,它才会触发过滤结果中的任何内容。有什么办法可以解决这个问题吗?我希望它只加载过滤后的结果一旦页面加载。

我是Angular JS的新手,但非常感谢任何形式的帮助或推动正确的方向。

我试过了:

ng-init="search.keywords='initial'"标签上输入,这似乎不会导致任何过滤发生。

$scope.search = { keywords: 'initial' };也会加载初始值,但不会触发任何过滤。

代码语言:javascript
复制
<input type="text" id="search-keywords" ng-model="search.keywords"
       class="form-control" placeholder="Keyword search">
代码语言:javascript
复制
$scope.$watch("search", function (newVal, oldVal) {
    if (newVal) {
        $scope.doFilter(newVal);
    }
}, true);


$scope.doFilter = function (search) {

    $scope.filtering = true;

    $scope.filteredCourses = $scope.filterExactMatchExceptNull($scope.courses, "inst", search.inst);

    $scope.filteredCourses = $scope.filterExactMatchExceptNull($scope.filteredCourses, "fos", search.fos);

    $scope.filteredCourses = $scope.filterCutoff($scope.filteredCourses, search.min, search.max);

    $scope.filteredCourses = $filter("filter")($scope.filteredCourses, {
        code: search.code,
        name: search.name,
        poa: search.poa
    });

    $scope.filteredCourses = $scope.filterByKeywords($scope.filteredCourses, search.keywords);

    $scope.limit = 15;

    if ($scope.limit >= $scope.filteredCourses.length) {
        $scope.limit = $scope.filteredCourses.length;
    }

    $scope.filtering = false;
};

$scope.filterByKeywords = function (courses, keywords) {
    if (!keywords || keywords == "") {
         return courses.filter(function (course) {
            return true;
        });
    } 

    var keywordArr = keywords.toLowerCase().trim().replace(/\W+/g, " ").replace(/\s\s+/g, " ").split(",");

         return courses.filter(function (course) {
             var matched = false;
             for (var i = 0, length = keywordArr.length; i < length; i++) {
                    if (course.keywords && course.keywords.indexOf(keywordArr[i]) > -1) {
                        matched = true;
                        break;
                    }
                }
                return matched;
            });
        };

任何帮助都将不胜感激!

EN

回答 2

Stack Overflow用户

发布于 2019-10-08 13:54:17

$watch函数用于检测加载到DOM中的输入字段中的任何更改。

因此,要第一次使用它,您可能会这样做:

要么在元素上使用ng-init,要么在DOM加载上触发过滤器方法。

代码语言:javascript
复制
ng-init="doFilter(search)"

在实际监视开始之前,在控制器级别调用过滤器函数一次。

代码语言:javascript
复制
$scope.search = { keywords: 'initial' }; 
$svope.doFilter($scope.search);
票数 2
EN

Stack Overflow用户

发布于 2019-10-08 13:51:23

您可以在ng-init指令中指定应该在页面初始化时执行的方法:

代码语言:javascript
复制
ng-init="doFilter({keywords: 'initial'})"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58280697

复制
相关文章

相似问题

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