我正在尝试加载一个在输入字段中预先填充了值的页面。页面和值确实会加载,但直到我在键盘上输入一些东西时,它才会触发过滤结果中的任何内容。有什么办法可以解决这个问题吗?我希望它只加载过滤后的结果一旦页面加载。
我是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;
});
};任何帮助都将不胜感激!
发布于 2019-10-08 13:54:17
$watch函数用于检测加载到DOM中的输入字段中的任何更改。
因此,要第一次使用它,您可能会这样做:
要么在元素上使用ng-init,要么在DOM加载上触发过滤器方法。
ng-init="doFilter(search)"或
在实际监视开始之前,在控制器级别调用过滤器函数一次。
$scope.search = { keywords: 'initial' };
$svope.doFilter($scope.search);发布于 2019-10-08 13:51:23
您可以在ng-init指令中指定应该在页面初始化时执行的方法:
ng-init="doFilter({keywords: 'initial'})"https://stackoverflow.com/questions/58280697
复制相似问题