2

im trying to display some rows in array, and filter them by some field.

for example:

i have the array "fieldindex", the fields in the array are:

  1. fieldname
  2. pageindex

and the array content is:

[{fieldname:'firstname',pageindex:'1'},{fieldname:'lastname',pageindex:'2'}]

and i have this code:

<input type="text" id="pageindex" />

    <span class="fieldindex" ng-repeat="x in fieldsonpdf">
    {{x.fieldname}}</span>

and i want the span to display only the fields that the 'pageindex' of them is equel to the input value

for example: if the value of the input is 1, the span display "firstname",

and if the value of the input is 2, the span display "lastname".

thanks for the helpers.

2 Answers2

2

You could add ng-model to the input like,

<input type="text" id="pageindex" ng-model="pageindex"/>

Then you can use the pageindex as filter to ng-repeat like,

<span class="fieldindex" ng-repeat="x in fieldsonpdf | filter:pageindex">

Working Snippet:

angular.module('test', [])
    .controller('test', ['$scope', function ($scope) {
    
    $scope.fieldsonpdf = 
    [
     {fieldname:'firstname',pageindex:'1'},
     {fieldname:'lastname',pageindex:'2'}
    ]
    
    $scope.pageindex = '1';
    
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="test" ng-controller="test">

    <input type="text" id="pageindex" ng-model="pageindex"/>

    <span class="fieldindex" ng-repeat="x in fieldsonpdf | filter:pageindex">
    {{x.fieldname}}</span>

</div>
Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
1

Let's consider that you have already the value from your input. You can use the function filter to bring all objects that match with your criteria or just find to get the first match, the best way is to add this code into your controller and the access from the template, using your example:

const list = [{fieldname:'firstname',pageindex:'1'},{fieldname:'lastname',pageindex:'2'}];

const getField = (value) => { return list.filter(item => +item.pageindex === value)}

then you just call from your template:

getField(2)

Be aware that I force the property item.pageindex to be a number using +.