0

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'
       }
3
  • Do you assign model1 and model2 to scope somewhere? This is probably a typo: $scope.mdoel1 Commented Dec 1, 2013 at 21:07
  • angular has a built in extend method docs.angularjs.org/api/angular.extend Commented Dec 1, 2013 at 21:09
  • sorry about the typo yes i have them bind with the html form values. and i have tried the extend method. it is not good for deep extend Commented Dec 1, 2013 at 21:13

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

create a demo in jsfiddle.net or plunker
i can easily change the $scope.model# to json but when i try to extend, it does not work. if the scope function was not working, it would not work for converting to json either. the problem is only when i extend these two models
it works like a charm!! thank you soo much!! and is there a way we can embed one model inside another?
is there way we can embed model_1 inside model_2 where model_2 will be a child of model_1?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.