来自另一个哈希列表的ng-bind过滤器值

时间:2015-01-22 06:58:30

标签: angularjs

$scope.myid = '1';
$scope.all = [{id: '1', name: 'one'},
              {id: '2', name: 'two'},
              {id: '3', name: 'three'}];

出于显示目的,我想显示所选id的名称。以下内容仅显示[object Object]

<span ng-bind="all | filter: {id: myid}"><span>

它还提供摘要警告:

10 $digest() iterations reached. Aborting!

如何绑定我选择的ID,而是显示其名称?

1 个答案:

答案 0 :(得分:1)

我认为这不是filter最恰当的用法。它实际上用于获取数组的子集。

您可以使用一个方法来获取具有特定ID的对象:

<span ng-bind="getObjectWithId(all, myid).name"></span>

控制器:

function AppController ($scope) {
    $scope.myid = '1';
    $scope.all = [{id: '1', name: 'one'},
        {id: '2', name: 'two'},
        {id: '3', name: 'three'}];

    $scope.getObjectWithId = function(array, id) {
        var match = null;
        angular.forEach(array, function(object, index) {
            if (object.id === id) {
                match = object;
            }
        });
        return match;
    }
}

angular
    .module('ModuleName', [])
    .controller('AppController', ['$scope', AppController]);

它基本归结为:

<span ng-bind="selectedObject.name"></span>
相关问题