角度1x:仅从2列过滤数据

时间:2018-11-06 21:32:09

标签: angularjs filter angularjs-1.6 angular1.6

我有关于Angular 1x的查询。如果任何内容仅与标题和内容匹配,我想过滤以下记录。我尝试将ng-model赋给我的输入,并像ng-repeat= t in t.items | filter:keyword一样应用了它,但是它正在使用link和其他所有列来过滤数据。

var myApp = angular.module('myApp',[]);

    myApp.controller('SearchController', ['$scope', function($scope) {

        $scope.results = [
            { title : "Cars", link: "http://tutorialedge.net", content: "lorem ipsum doler fox pixel"},
            { title : "Boats", link: "http://tutorialedge.net", content: "lorem ipsum doler cat pixel"},
            { title : "Vans", link: "http://tutorialedge.net", content: "lorem ipsum doler pig pixel"},
            { title : "Limos", link: "http://tutorialedge.net", content: "lorem ipsum doler pixel"}
        ];

    }]);

是否可以仅从2列中过滤数据?

编辑

我有一个<input type="search" />,我想在用户开始输入内容后立即过滤数据,但它应该只在两列中搜索关键字。

3 个答案:

答案 0 :(得分:0)

看看https://docs.angularjs.org/api/ng/filter/filter,它说明一切都很好。对于您的问题,您可以这样做:

组件的控制器:

$scope.results = [
        { title : "Cars", link: "http://tutorialedge.net", content: "lorem ipsum doler fox pixel"},
        { title : "Boats", link: "http://tutorialedge.net", content: "lorem ipsum doler cat pixel"},
        { title : "Vans", link: "http://tutorialedge.net", content: "lorem ipsum doler pig pixel"},
        { title : "Limos", link: "http://tutorialedge.net", content: "lorem ipsum doler pixel"}
    ];

$scope.mySubstringExpression = "Vans";

$scope.myFancyFilter = function(element) {
    return element.title.indexOf(mySubstringExpression) > -1 || element.contant.indexOf(mySubstringExpression) > -1;
};

然后进入组件模板:

<div ng-repeat="item in results | filter:myFancyFilter"> 

答案 1 :(得分:0)

另一种方法:

$scope.filterResult = []
$scope.filterParams = {
    title = "all",
    content = "all"
}
$scope.filter = function (){
    if($scope.filterParams.title == "all" && $scope.filterParams.content == "all") {
        $scope.filterResult = $scope.results
    } else {
        $scope.filterResult = $scope.results.filter(x => 
            x.title == $scope.filterParams.title && 
            x.content == $scope.filterParams.content)
    }
}

然后,您只需要在$ scope.filterResult上使用ng-repeat

<div ng-repeat="item in filterResult"> 

您只需要在$ scope.filterParams中使用ng-model,并且每次更改过滤器时,只需调用$ scope.filter()即可更新$ scope.filterResult。

答案 2 :(得分:0)

您可以使用这种方法来实现

ng-repeat=" t in t.items | filter: {'title': 'Cars'}: true"