【问题标题】:Angular Filter for Object对象的角度过滤器
【发布时间】:2017-03-21 05:08:28
【问题描述】:

我正在尝试使用过滤器,以便使用带有名称 ID 的 ng-options 从选择元素中匹配新选择的名称。

我正在使用的对象如下所示:

 $scope.fish = {1:'Ben', 2: 'Rich', 3:'John'}

现在选择默认设置为“John”。当用户将选择选项更改为“Rich”时,我希望过滤器功能返回 2(这是 Rich 对应的 ID)。

假设:

$scope.selectedFish

只存储鱼的名称而不是 ID。

JSFiddle

【问题讨论】:

    标签: angularjs object filter


    【解决方案1】:

    你可以这样做,

    <div data-ng-app="market">
      <div data-ng-controller="SomeController">
        <select ng-model="selectedFish" ng-options="key as value for (key , value) in fish" ng-change="getIdByName()"></select>
      </div>
    </div>
    

    控制器:

    app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
      $scope.fish = {
        1: 'Ben',
        2: 'Rich',
        3: 'John'
      }
      $scope.getIdByName = function() {
        angular.forEach($scope.fish, function(value, key) {
          if (key == $scope.selectedFish) {
            console.log("selected key is " + $scope.selectedFish + "selected value is " + value);
          }
        });
      }
    
    }]);
    

    DEMO

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    尝试使用以下解决方案

    $scope.fish = {1:'Ben', 2: 'Rich', 3:'John'};
    $scope.selected = 'Rich';
    
    var getValue = function(){
        var result = "";
        angular.forEach($scope.fish, function(value, key) {
            if (value == $scope.selected) {
               result = key;
            }
        });
        console.log(result);
        return result;
    }
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢,你和 Sajeetharan 基本上有相同的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    相关资源
    最近更新 更多