gpt4 book ai didi

javascript - Lodash 和 Angular : Transform JSON object into view model

转载 作者:行者123 更新时间:2023-12-03 07:45:58 25 4
gpt4 key购买 nike

我正在尝试找到将大型 JSON 对象转换为 View 模型的最佳方法。以前,我将模型合并到 View 中,这是一个不好的做法。所以,现在我已经在 Controller 内部生成了模型。我使用 Lodash 作为实用程序库。

我当前的设计计划是将 JSON 对象转换为可在 Controller 范围内访问的“主”数组。 JSON 文件由 Express 提供。 ModelService 只需获取此文件即可使其在 Controller 中可用。

$scope.arr 是我想在 View 中使用的“主”数组。

我还使 JSON 数据可供通过外部链接查看,因为它太大了。 Here it is .

(function() {
'use strict';

angular
.module('app')
.controller('ModelController', ModelController);

function ModelController($scope, ModelService, _) {
$scope.jsonData = ModelService.getAll();

$scope.getData = function() {
$scope.jsonData.$promise.then(function(data) {
$scope.all = data;
$scope.arr = [];
_.mapValues($scope.all.parent1.clusters, function(cluster) {
$scope.arr.push(cluster.name);
_.mapValues(cluster.subclusters, function(subcluster) {
$scope.arr.push(subcluster.name);
_.mapValues(subcluster.entities, function(entity) {
// map entities
})
});
});
});
};

$scope.getData();
}
})();

此代码只是将clustersubcluster 名称添加到数组中。我希望将子集群映射到其父集群。我这样做的想法包括将每个簇元素转换为自己的数组,然后添加子簇,然后将每个子簇转换为数组以便将实体映射到它们。这看起来既乏味又低效。因此,我正在寻找更好的方法来实现这一目标。

如果我可以将每个簇对象一次性添加到数组中,而无需将所有对象映射和转换为数组,那就太好了。这可能吗?

线框 View 看起来像 thisFlex 集群标题子集群的名称,其中的每个数字都是一个实体

最佳答案

首先,我会将此处理移至服务中。它更容易测试,并使您的 View 与模型分离(在我看来,当涉及到 Angular 时, Controller 实际上更多地是“ View ”的一部分,特别是如果您考虑将来升级到 Angular 2.0)。

在 Angular 中,我认为解决这个问题的适当方法是使用组件(或指令)与 ng-repeat 结合使用。

页面模板:

<!-- Page template, assume $ctrl is your controller, $ctrl.clusters is the data -->
<cluster ng-repeat = "cluster in $ctrl.clusters"
cluster-data="cluster" >
</cluster>

集群指令模板:

<!-- Assume $ctrl is the controller for the cluster directive, $ctrl.cluster is the cluster object. -->
<div class="name">{{$ctrl.cluster}}</div>
<div class="subClusterNames"
ng-repeat="subCluster in $ctrl.cluster.subClusters>
{{subCluster.name}}
</div>

您可能认为这将您的数据映射到 View 太接近,但是只要您使用组件来显示数据(即,不要将其全部放入一个模板中)我我想你会没事的。

关于javascript - Lodash 和 Angular : Transform JSON object into view model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com