繁体   English   中英

使用ng-repeat获取具有不同名称的嵌套对象的值

[英]Getting values for a nested object with different names using ng-repeat

我有一个JSON对象,每个属性都有不同的名称,如下所示:

var definitions = {
  foo: {
    bar: {abc: '123'},
    baz: 'def'
  },
  qux: {
    broom: 'mop',
    earth: {
      tree: 'leaf',
      water: 'fish'
    },
    fig: {
      qwerty: 'olive'
    }
  },
  blix: {
    worm: 'dirt',
    building: 'street'
  }
  ... more nested objects
};

现在,我正在显示这样的数据:

<div class="type" ng-repeat="(key,val) in definitions">
  <h4 ng-model="collapsed" ng-click="collapsed=!collapsed">{{key}}</h4>
  <div ng-show="collapsed">{{val}}</div>
</div>

这是我的控制器:

App.controller('DefinitionsCtrl', function ($scope) {
  $scope.definitions = definitions;
});

{{val}}只是在单击其各自的{{key}}时显示该属性的精简字符串。 我想进一步正确解析val部分,所以例如foo的嵌套属性( barbaz )将分别拥有自己的div。 但是,我想对所有嵌套值执行此操作。 手动执行此操作不是一个选项(它是一个巨大的文件)。

考虑到所有嵌套名称都不同,这可能吗? 我是否必须创建一个自定义过滤器,或者这是我应该在控制器中处理的东西?

所以,如果我理解正确,你想要一个递归的ng-repeat? 最好的办法是创建一个自定义指令。

看看这个递归的示例指令:

.directive('collection', function () {
return {
    restrict: "E",
    replace: true,
    scope: {
        collection: '='
    },
    template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
}
})

.directive('member', function ($compile) {
return {
    restrict: "E",
    replace: true,
    scope: {
        member: '='
    },
    template: "<li>{{member.name}}</li>",
    link: function (scope, element, attrs) {
        // this is just un-compiled HTML, in the next step we'll compile it
        var collectionSt = '<collection collection="member.children"></collection>';
        if (angular.isArray(scope.member.children)) {       
            //compile and append another instance of collection
            $compile(collectionSt)(scope, function(cloned, scope)   {
                element.append(cloned); 
              });
        }
    }
}
})

看到它在这里运行: http//jsbin.com/acibiv/4/edit和一篇关于它的博客文章: http//sporto.github.io/blog/2013/06/24/nested-recursive-directives-in -angular /但不遵循博客文章中的代码,这是不正确的。 他没有正确编译。

当然,这需要您进行大量定制。 而不是检查“孩子”,你必须检查你的价值是否是一个对象。

暂无
暂无

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

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