【发布时间】: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