簡體   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