Andy59469
Andy59469

Reputation: 2064

AngularJS search array of objects

I have an array of objects in my controller eg:

$scope.fields = [
    {fieldName:'houseNum',fieldLabel:'House Number',disabled:false},
    {fieldName:'street',fieldLabel:'Street',disabled:false},
    {fieldName:'city',fieldLabel:'City',disabled:true},
    {fieldName:'state',fieldLabel:'State',disabled:true},
]

In the HTML I would like to be able to get a fieldLabel where fieldName=='street'. The AJS documentation presumes that every filter case should be in the context of ng-repeat - but not so in my case as I am just trying to pluck one 'fieldLabel' from the 'fields' array based on 'fieldName'

eg: HTML

{{ fieldLabel in fields | filter : {fieldName:'street'} : true}}

How can I make something like this work - or do I need to create my own directive and pass the $scope.fields to the directive and loop through manually?

Upvotes: 4

Views: 7718

Answers (1)

PSL
PSL

Reputation: 123749

You could do:

{{ (fields | filter : {fieldName:"street"} : true)[0].fieldLabel}}

(fields | filter : {fieldName:"street"} : true) returns an array of filtered items get the first one [0] and access fieldLabel property out of that object.

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.fields = [{
    fieldName: 'houseNum',
    fieldLabel: 'House Number',
    disabled: false
  }, {
    fieldName: 'street',
    fieldLabel: 'Street',
    disabled: false
  }, {
    fieldName: 'city',
    fieldLabel: 'City',
    disabled: true
  }, {
    fieldName: 'state',
    fieldLabel: 'State',
    disabled: true
  }, ]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  {{ (fields | filter : {fieldName:"street"} : true)[0].fieldLabel}}
</div>

Though better option would be to set the property from the controller itself, so that the filter does not run during every digest cycle.

function getFieldByName(prop){
     var field = {};
     //Or just use a for loop and break once you find a match
     $scope.fields.some(function(itm){
         if(itm.fieldName === prop){
            field = itm;
            return true;
         }
     });
     //Or you could inject $filter as well an do as below
     //return $filter('filter')($scope.fields,{fieldName:"street"})[0] || {}
     return field;
}

//Somewhere
$scope.streetField = getFieldByName('street');

In the view:

{{streetField.fieldLabel}}

Array.some

Upvotes: 5

Related Questions