【问题标题】:Concatenate two scope models in angularjs在angularjs中连接两个范围模型
【发布时间】:2013-12-17 12:07:31
【问题描述】:

您好,我正在尝试连接两个由 html 表单值绑定的模型。我的最终目标是为 POST 请求创建一个嵌套的 JSON 对象。我尝试使用下面的DeepExtend 方法,但它仅适用于非 $scope 对象。我真的很想知道为什么会这样。

这是我在这个问题上的尝试

as.factory('model1', [
    function () {
        return {
            Header1: {
                code: '',
                name: '',
                type: ''

            }
        };

    }
]);


as.factory('model2', [
    function () {
        return {
            Header2: {
                code2: '',
                name2: '',
                country: ''
            }
        };

    }
]);

as.controller('cntrl', function ($scope, $http, i18n, $rootScope, model1, model2) {

    function deepObjectExtend(target, source) {
        for (var prop in source)
            if (prop in target)
                deepObjectExtend(target[prop], source[prop]);
            else
                target[prop] = source[prop];
        return target;
    }

    var result = deepObjectExtend($scope.mdoel1, $scope.model2);
    $rootScope.resultString = angular.toJson(result);
    console.log($rootScope.resultString);
});

我的最终结果应该是:

Header1: {
        code:'123',
        name: '321',
        type:'123'               
       },
Header2: {
        code2:'123' ,
        name2: '123',
        country: '123'
       }

【问题讨论】:

  • 您是否将模型 1 和模型 2 分配给某处的范围?这可能是一个错字:$scope.mdoel1
  • angular 有一个内置的扩展方法docs.angularjs.org/api/angular.extend
  • 抱歉错字是的,我让它们与 html 表单值绑定。我已经尝试过扩展方法。它不适合深度扩展

标签: javascript json angularjs extend concat


【解决方案1】:

似乎您想从两个模型中创建一个新对象。

如果是这样,你可以这样做:

var result={}
 angular.extend(result, $scope.model1, $scope.model2);

【讨论】:

  • 在 jsfiddle.net 或 plunker 中创建一个演示
  • 我可以轻松地将 $scope.model# 更改为 json,但是当我尝试扩展时,它不起作用。如果作用域函数不起作用,则转换为 json 也不起作用。问题只是当我扩展这两个模型时
  • 它就像一个魅力!非常感谢你!!有没有办法可以将一个模型嵌入到另一个模型中?
  • 有没有办法可以将 model_1 嵌入到 model_2 中,其中 model_2 将是 model_1 的子节点?
猜你喜欢
  • 2018-12-18
  • 1970-01-01
  • 2018-12-19
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
相关资源
最近更新 更多