AngularJS搜索对象数组

时间:2015-06-03 18:17:43

标签: javascript arrays angularjs filter

我的控制器中有一组对象,例如:

$scope.fields = [
    {fieldName:'houseNum',fieldLabel:'House Number',disabled:false},
    {fieldName:'street',fieldLabel:'Street',disabled:false},
    {fieldName:'city',fieldLabel:'City',disabled:true},
    {fieldName:'state',fieldLabel:'State',disabled:true},
]

在HTML中,我希望能够获得fieldName =='street'的fieldLabel。 AJS文档假定每个过滤器案例都应该在ng-repeat的上下文中 - 但在我的情况下不是这样,因为我只是试图从'field'数组中根据'fieldName'从一个'fieldLabel'中取出'fieldLabel'

例如:HTML

{{ fieldLabel in fields | filter : {fieldName:'street'} : true}}

我怎样才能做出像这样的工作 - 或者我是否需要创建自己的指令并将$ scope.fields传递给指令并手动循环?

1 个答案:

答案 0 :(得分:5)

你可以这样做:

{{ (fields | filter : {fieldName:"street"} : true)[0].fieldLabel}}

(fields | filter : {fieldName:"street"} : true)返回过滤后的项目数组,获取该对象中的第一个[0]fieldLabel属性。



angular.module('app', []).controller('ctrl', function($scope) {
  $scope.fields = [{
    fieldName: 'houseNum',
    fieldLabel: 'House Number',
    disabled: false
  }, {
    fieldName: 'street',
    fieldLabel: 'Street',
    disabled: false
  }, {
    fieldName: 'city',
    fieldLabel: 'City',
    disabled: true
  }, {
    fieldName: 'state',
    fieldLabel: 'State',
    disabled: true
  }, ]
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  {{ (fields | filter : {fieldName:"street"} : true)[0].fieldLabel}}
</div>
&#13;
&#13;
&#13;

虽然更好的选择是从控制器本身设置属性,以便过滤器在每个摘要周期内都不会运行。

function getFieldByName(prop){
     var field = {};
     //Or just use a for loop and break once you find a match
     $scope.fields.some(function(itm){
         if(itm.fieldName === prop){
            field = itm;
            return true;
         }
     });
     //Or you could inject $filter as well an do as below
     //return $filter('filter')($scope.fields,{fieldName:"street"})[0] || {}
     return field;
}

//Somewhere
$scope.streetField = getFieldByName('street');

在视图中:

{{streetField.fieldLabel}}

Array.some