javascript - 在 Angular JS 上预填充关键字搜索过滤器

标签 javascript angularjs

我正在尝试加载一个在输入字段中预填值的页面。页面和值确实会加载,但它不会在过滤结果中触发任何内容,直到我在键盘上输入内容。有没有解决的办法?我希望它在页面加载后只加载过滤后的结果。

我是 Angular JS 的新手,但感谢任何形式的帮助或插入正确的方向。

我试过:

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

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

<input type="text" id="search-keywords" ng-model="search.keywords"
       class="form-control" placeholder="Keyword search">
$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;
            });
        };

如有任何帮助,我们将不胜感激!

最佳答案

$watch 函数用于检测输入域加载到 DOM 后的任何变化。

因此,第一次使用它时,您可以:

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

ng-init="doFilter(search)"

或者

在实际 watch 开始之前,在 Controller 级别本身调用一次过滤器功能。

$scope.search = { keywords: 'initial' }; 
$svope.doFilter($scope.search);

关于javascript - 在 Angular JS 上预填充关键字搜索过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58280697/

相关文章:

javascript - 静态方法中的 setState

javascript - 如何绑定(bind)到一些返回 Promise 的函数来表达路由?

javascript - 字符串数组因意外 token javascript 引发错误

javascript - 如何在 Google map 中添加我的位置按钮?

javascript - Breeze js 调用元数据但不会对服务器进行第二次调用

javascript - 在 Es6 中添加模板后点击事件

javascript - 从json数组中获取选定的 ionic 复选框

javascript - Auth0 与 Angular 1.5.8 和 webpack

iOS Safari 选择禁用复制/定义/共享..链接

javascript - 无法获取从服务中填充的 $scope.data Angular