简体   繁体   English

从角度对象数组中获取特定对象

[英]Get a specific object from an object array in angular

This is my object array and it is bound to a dropdownlist: 这是我的对象数组,它绑定到一个下拉列表:

$scope.dropdownOptions = [{value: "0", name: 'No'}, {value: "1", name: 'Yes'}];

I want to return the corresponding "Name" depending on the selected "Value" in the dropdown through the following function. 我想通过以下函数根据下拉列表中选择的“值”返回相应的“名称”。 Right now I have hardcoded the return values. 现在,我已经对返回值进行了硬编码。

$scope.getDropdownDisplayValue = function(_key){
    if(_key == "1")
      return "Yes";
    else if(_key == "0")
      return "No";
    else
      return "n/a";
  };

The problem is, if I modify the Names property of objects in that array I will have to come and change the return values of the above function as well. 问题是,如果我修改该数组中对象的Names属性,则必须同时更改上述函数的返回值。 To Avoid that, I want to serach the object array and return the corresponding value. 为了避免这种情况,我想搜索对象数组并返回相应的值。 For example: 例如:

$scope.getDropdownDisplayValue = function(_key){
        if(_key == "1")
          return <get object.name where object.value == _key from dropdownOptions array>
        else if(_key == "0")
          return <get object.name where object.value == _key from dropdownOptions array>
        else
          return "n/a";
      };

I can write a custom function for that, but want to whether I can use something already available in AngularJS or JavaScript. 我可以为此编写一个自定义函数,但是要确定我是否可以使用AngularJS或JavaScript中已经可用的功能。 Thanks in advance. 提前致谢。

Is this you wanted? 这是你想要的吗?

fiddle 小提琴

angular.module('demoApp', []).controller('DemoController', function($scope) {

  $scope.options = [
    { label: 'one', value: 1 },
    { label: 'two', value: 2 }
  ];

  // Although this object has the same properties as the one in $scope.options,
  // Angular considers them different because it compares based on reference
  $scope.incorrectlySelected = { label: 'two', value: 2 };

  // Here we are referencing the same object, so Angular inits the select box correctly
  $scope.correctlySelected = $scope.options[1];
});

index.html: index.html:

<select ng-model="incorrectlySelected"
            ng-options="opt as opt.label for opt in options">
        </select>

above is example from the angularJS official website 以上是angularJS官方网站上的示例

Yes, you can use filterFilter service. 是的,您可以使用filterFilter服务。

For example 例如

app.controller('ExampleCtrl', ['$scope','filterFilter', function($scope, filterFilter) 
{

   $scope.dropdownOptions = [{value: "0", name: 'No'}, {value: "1", name: 'Yes'}];

   $scope.getDropdownDisplayValue = function(_key) {
      var objs = filterFilter($scope.dropdownOptions , {value: _key});
      if( objs.lenght > 0) {
        return objs[0].name;
      } else {
        return 'n/a';
      }
   };

 }]);

Hope this help. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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