AngularJs - 按键在数组中查找对象,并在View中显示其值

时间:2021-05-16 21:28:00

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."

在Controller中我想要在View中显示值。上面的例子应该给我“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)?

它有效,但使用ng-repeat感觉不对。有没有更好的方法(没有创建另一个功能)?

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?

它最初显示“value2”,但在更改输入字段的值后没有显示任何内容。这是为什么?

1 个解决方案

#1


0  

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>

#1


0  

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>