Angular 1x: filter data from 2 columns only

75 Views Asked by At

I have query about Angular 1x. I want to filter the below records if anything matches with title and content only. I tried giving ng-model to my input and applied the same like ng-repeat= t in t.items | filter:keyword but it is filtering the data with link and all other columns as well.

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"}
        ];

    }]);

Is it possible to filter data from 2 just columns?

Edit

I have a <input type="search" /> and I want to filter data as soon as user starts typing but it should search the keywords in just two columns.

3

There are 3 best solutions below

0
On

Have a look at https://docs.angularjs.org/api/ng/filter/filter it explains everything pretty good. For your question you can do it like:

Component's controller:

$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;
};

Then in component's template:

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

Another approach:

$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)
    }
}

Then you just have to use the ng-repeat over $scope.filterResult

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

and you just have to use ng-model with $scope.filterParams, and every time you change the filter just call $scope.filter() and the $scope.filterResult will be updated.

0
On

you can achieve this by using this approach

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