简体   繁体   中英

AngularJs - Find an object in an array by key and display its value in View

Say I have an object array:

$scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}];

And a variable that should map to key . For example:

$scope.a = 3;

With both in Controller I want to display the value in View. The above example should give me "value3."

Without creating another function, I do something like:

<span ng-repeat="obj in objArr | filter:{key:a}:true">{{obj.value}}</span>

It works but using ng-repeat feels wrong. Is there any better way (without creating another function)?

EDIT:

This is the full code I'm using:

  <body ng-app="myApp">
    <div ng-controller="MyController">
        <span ng-repeat="obj in objArr | filter:{key:a.test}:true">{{obj.value}}</span>
        <input ng-model="a.test"/>
    </div>
  </body>

Controller:

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

myApp.controller('MyController',function($scope){
  $scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}];
  $scope.a = {test:2}
});

It is initially showing "value2", but shows nothing after I change the value of the input field. Why is that?

You can try this

you can create a method inside your controller

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

 myApp.controller('MyController',function($scope){
    $scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}];
    $scope.callSearch = function(num) {
    var abc = filterFilter($scope.objArr, {id: num});
    $scope.item= abc[0].value;
  };
});

In your View you can do this

<div ng-controller="MainController">
  <input ng-model="search"/>
  <button ng-click="callSearch(search);">Search</button>
 {{item}}  
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM