Using ng-Options how do I filter that exactly interprets the reported value

Asked

Viewed 171 times

2

I’ll give you an example just for testing:

In this example when I put filter:chart.id='1', in addition to it returning me id 1 it returns me id 10, as I would return only id=1?

function TodoCtrl($scope) {
    
  $scope.chartList = [ 
    { "id" : 1, "name" : "chart 1", "order" : 1, "active" : false },
    { "id" : 2, "name" : "chart 2", "order" : 2, "active" : false },
    { "id" : 3, "name" : "chart 3", "order" : 3, "active" : true },
    { "id" : 4, "name" : "chart 4", "order" : 4, "active" : true }, 
    { "id" : 10, "name" : "chart 10", "order" : 5, "active" : true }
  ];
}
.done-true {
  text-decoration: line-through;
  color: grey;
}
<div ng-app>
  <div ng-controller="TodoCtrl">
    <select ng-model="toAddChart" ng-options="chart.id as chart.name for chart in chartList | filter:chart.id='1'">
      <option value=""></option>
    </select>
  </div>
</div>

1 answer

3

Depending on the version of Angularjs you are using you can force it to make an exact comparison by passing true as a parameter for the filter

ng-options="chart.id as chart.name for chart in chartList | filter:chart.id=1:true"

But you must take into account that the comparison in this way is exact, so in your example there were simple quotes in filter:chart.id='1', notice that I removed them in my example, with them it would not work because it would compare a text with a number and the result would be false.

In older versions of Angularjs you can create a function to make this filter

$scope.meuFiltro = function(valor){
    return function(obj){
        return obj.id == valor;
    }
};

Then use it to pass the value you want to filter

ng-options="chart.id as chart.name for chart in chartList | filter:meuFiltro(1)"
  • It worked! Just by doubt from which version the true parameter works?

  • From the documentation it seems to be from version 1.1.3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.