Question

Hello Im trying to concatenate two models which are bound by html form values. My ultimate goal is to create a nested JSON object for a POST request. I have tried to use the DeepExtend method like below but it only works for non $scope objects. I really want to know why is this happening.

This is my try on the issue

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);
});

My final result should be:

Header1: {
        code:'123',
        name: '321',
        type:'123'               
       },
Header2: {
        code2:'123' ,
        name2: '123',
        country: '123'
       }
Was it helpful?

Solution

seems like you want to create a new object out of the two models.

If so you could do:

var result={}
 angular.extend(result, $scope.model1, $scope.model2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top