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

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


我是 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;

            });

        };

任何帮助将不胜感激!


手掌心
浏览 103回答 2
2回答

缥缈止盈

$watch 函数用于检测输入字段在加载到 DOM 后的任何变化。所以,第一次使用它,你可以这样做:在元素上使用 ng-init 以在 DOM 加载时触发过滤器方法。ng-init="doFilter(search)"或者在实际监视开始之前,在控制器级别本身调用过滤器函数一次。$scope.search = { keywords: 'initial' };&nbsp;$svope.doFilter($scope.search);

慕斯王

您可以在 ng-init 指令中指定应该在页面初始化时执行的方法:ng-init="doFilter({keywords:&nbsp;'initial'})"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript